简体   繁体   中英

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'.

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

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,}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM