Home > Net >  Regex IsMatch stops matching
Regex IsMatch stops matching

Time:10-08

I'm writing a checker with Regex, and I'm testing results with one of the popular tools: enter image description here

that one little detail is missing: @ in your code. The page will add it for you

private bool IsProcessColumn(string column)
{
    return Regex.IsMatch(column, @"Process(. )\\. ");
}

Here is a fiddle for testing

Explanation: The problem is that the character \ is a special character and in the context of regex also ambiguous.

  1. It is used as escape character in a normal string.
  2. In Regex it is used for special characters like \d (digits) and to mark the real character like: \. (matching a real dot)

So without the @ the pattern is interpreted as looking for a dot because the first backslash is an escape character that makes the second backslash to a modifier for regex which is applied to the dot: \.. You can test it by inserting a dot into the last string:

string a5 = "Process(DcCutting)\\%. Processor Time";

and you will have a match with your original pattern.

Using the @ (which means that you don't need to escape special characters) results in the first backslash being treated already as a modifier for regex which is then applied to the second backslash: \\ which tries to match a real backslash in the string, and the . is then interpreted as a wildcart.

Sounds horribly complicated. I hope I was at least a little understandable

  • Related