Im frustrated
Im frustrated

Reputation: 27

C# Regular Expressions search

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

  1. Whole word search for (A) should return a match.
  2. Whole word search for A should not return a match.
  3. Partial word search for A should return a match.
  4. Whole word search for (( 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

Answers (1)

Jonesopolis
Jonesopolis

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

Related Questions