0
Regex r = new Regex(Regex.Escape("(st)"));
//or Regex r=new Regex(@"\(st\)");
int c = r.Matches("test string").Count;

The result should be c=2, but c is 0. https://regex101.com/ also gives 2 matches.

Regex("st") will give 2 matches with no doubt. But what is needed here is to match a word in a list and after the failure, to be simple the above test code has only one entry.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
jw_
  • 1,663
  • 18
  • 32

2 Answers2

3

What you've done wrong here, is passed your pattern through Regex.Escape. What this will do, is escape your brackets so your pattern will actually be @"\(st\)".

When working with Regular expressions, I like to use verbatim string literals. This means you can write the pattern as you need, including backslashes. Change your code to the following:

var regex = new Regex(@"(st)");

And your regular expression will match.

As an added bonus, using C#'s verbatim strings means you can copy-paste your pattern from sites like Regexr.com without worrying about escaping them. Only becomes a problem when you're using quotes ("), but even then there's ways around that are easy.


EDIT If you're looking to match the word at it's boundary, you will need to use \b.

var regex = new Regex(@"(st\b)"); // Or remove the brackets entirely, up to you. 

If you're looking to match a word beginning with the string, use \w (for word).

Regexr.com has a great cheat sheet that's worth checking out.

SimonC
  • 1,547
  • 1
  • 19
  • 43
1

You should not escape ( and ); either use "st" pattern or "(st)" (a group which contains "st").

Let's have a look what's going on

string test = "test string";

string[] patterns = new string[] {
  "st",                 // just "st"
  "(st)",               // a group which contains "st"
  Regex.Escape("st"),   // just "st" (nothing to escape)
  Regex.Escape("(st)")  // ( and ) are escaped, now we are looking for "(st)" substring
}

string report = string.Join(Environment.NewLine, patterns
  .Select(pattern => 
     $"pattern: {pattern,-10} : matches : {Regex.Matches(test, pattern).Count}"));

Console.Write(report);

Outcome:

pattern: st         : matches : 2 // Just "st"
pattern: (st)       : matches : 2 // A group contains "st"
pattern: st         : matches : 2 // Escaped "st" we have nothing to escape
pattern: \(st\)     : matches : 0 // Escaped '(' and ')' which are not matched
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215