简体   繁体   中英

C# Regex why 2 \\ needed in the following example?

This is from an example from MS. I don't understand why in Mr.\\.? etc. there are 2 escape chars in C#, in a regex-tester one has to write only Mr.?, so it must be C# specific.

public static void Main()
{
   string pattern = "(Mr\\.? |Mrs\\.? |Miss |Ms\\.? )";
   string[] names = { "Mr. Henry Hunt", "Ms. Sara Samuels", 
                      "Abraham Adams", "Ms. Nicole Norris" };
   foreach (string name in names)
      Console.WriteLine(Regex.Replace(name, pattern, String.Empty));
} 

There are two things going on here. In c# there are certain chars in strings which require an escape sequence:

https://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx

A character that follows a backslash character () in a regular-string-literal-character must be one of the following characters: ', ", \\, 0, a, b, f, n, r, t, u, U, x, v. Otherwise, a compile-time error occurs.

So the first backslash is to make the string valid - it has nothing to do with Regex's.

The second thing going on is that the period means "match any character" in the Regex so to match an actual period it must be escaped with a single slash.

The single slash requires a second slash simply to make the string literal valid.

You need the \\ to escape the . character and you have to use 2 \\ so that the first \\ is escaped also.

Mr.   - means match Mr[anything] 
Mr\.  - means match Mr\[anything]
Mr\\. - means match Mr.

I hope this is understandable.

I found the solution by looking up the properties of a regular string - as oposed to a verbatim string - in C#. Inside a string " " a \\ can only be used in combination with certain characters, for example one can use \\t oder \\n, but . is not allowed. So to get the output (Mr. one has to write "(Mr\\., so that the first \\ escapes the second .

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