mcqwerty
mcqwerty

Reputation: 225

C# Regex doesn't match but regex testers do match

 var pattern = @"[\S\s][0-9]{1,}\e[0-9]{1,}";
 var regEx = new Regex(pattern);

This yields zero matches when run against this string:

"Show name - s01e08 - Episode name.mp4"

These regex testers get a match: http://www.regexr.com/ http://regexpal.com/

but this one that clams to be a .Net regex tester does not get a match: http://regexhero.net/tester/

Which is what I am experiencing in my app.

  1. Why is there a difference?
  2. How do I 'fix' my regex pattern to get a match in my C# app?

Sidenote: The actual pattern I would like to use is:

"[\S\s][0-9]{1,}[\E\e][0-9]{1,}"

But this gives me a 'Unrecognized escape sequence \E.' error in both the .Net regex tester and my C# app. I will create a new SO question for this but wanted to mention it here as I'm sure someone will notice my original pattern will not catch upper case 'E'.

Upvotes: 1

Views: 1251

Answers (2)

Ameen
Ameen

Reputation: 2586

It looks like you are trying to write a RegEx for .NET without really using its syntax. .NET does not use Posix syntax is what you might be using.

Some mistakes that I can call:

  • When you want to match a letter, you should not espace it. You don't need any \ before it. To match an upper case E, just use E
  • \s matches whitespace in .NET. If you want to match a lowercase s, just write s

Here is what your pattern means:

[\S\s] match one space character (\s) or one non-whitespace character (\S)
[0-9]{1,} match a digit (0 to 9) 1 times or more
\e match one escape character
[0-9]{1,} match a digit one or more times

Upvotes: 4

BlackBear
BlackBear

Reputation: 22979

Your pattern should be

[sS](?<Season>\d+)[eE](?<Episode>\d+)

You basically do not have to escape characters inside range specifiers, and \d+ is a more concise way of writing [0-9]{1,}

Upvotes: 2

Related Questions