I am using the following regular expression in java to try and find if the pattern is either in the beginning of a string, at the end of the string, or surrounded by white space but it is not working.
If I do this \\Wmypattern\\W it finds patterns surrounded by white space.
But if I do this [^\\W]mypattern[\\W$] it does not. The latter regular expression is my attempt to get it to match if pattern exists in the beginning of the string, the end of the string or starts at the beginning or ends at the end of string.
What am I doing wrong?
You want to use
This will match either a non-word character or the beginning of the string at the beginning of the pattern and either a non-word character or the end of the string at the end of the pattern.
Your current pattern matches a single character that is not a non-word character (
[^\\W]) followed by your pattern, and followed by either a non-word character or the literal character$([\\W$])This page is a good reference for regular expression syntax