Reputation: 27
I am using regular expressions to search some text (an equation).
I might have something like this
(A) (x + 5) (( testthis ))
I have an option to search for the whole word only or for partial words.
Here are a few conditions for the above example that I'd like to meet, but don't seem to work with any options that I've tried
(A)
should return a match.A
should not return a match.A
should return a match.((
should return a match since there is a space on each side of the brackets around (( testthis ))
.I have tried the code below as well as many other combinations such as \\b \\b* \\S* \\W
.
I basically want the same functionality as \b but with support for non-alphanumeric characters.
if (bWholeword == true)
{
matchText = "\\s*" + Regex.Escape(term) + "\\s*";
}
else
{
matchText = Regex.Escape(term);
}
Upvotes: 0
Views: 215
Reputation: 25370
matchText = bWholeword
? (@"(^|(?<=[\b\W|_]))" + term + @"($|(?=[\b\W|_]))")
: term;
(^|(?<=[\b\W|_]))
matches either the start of the string, or any non-alphanumeric (only grabbing the term though). And same for the end.
It's gets tricky when your term is (
or similar. It will match once on each (
because they are both whole words, around nonalphanumeric characters.
Upvotes: 1