c# – Regex for newline “nr” and digits
What should it look like?
Table of Contents
If your string contains carriage return and line feed characters
If, when you said in your post like bla rn1.1
, you mean this string has one carriage return and one line feed and 9 characters total, then you can:
Regex.Match("blabla rn1.1 Entrepreneurship und Untern", "rn\d\.\d\s+");
(you don’t need to \r\n
because the regex engine will be OK with receiving CR LF as actual chars made by the compiler interpreting r and n, but the compiler won’t appreciate you putting d and s in a non-verbatim string because these aren’t known escape sequences the compiler can handle)
Or
Regex.Match("blabla rn1.1 Entrepreneurship und Untern", @"rnd.ds+");
In this second form it’s the Regex engine, not the compiler, that receives r
and interprets it as “carriage return”. Using @ turns off the compiler’s process of converting any r
it sees to a carriage return character (char 13). This means it’s the regex engine that sees r
and interprets it as “the user is looking for a carriage return character”
If your string contains slash, r, slash, n characters
If, when you said in your post like bla rn1.1
, you mean this string has literally a slash and an r, and a slash and an n for 11 characters total, then you can:
Regex.Match(@"blabla rn1.1 Entrepreneurship und Untern", "\\r\\n\d\.\d\s+");
You need to put \\r
because the compiler will turn this into \r
, and the Regex engine will then turn this into r
which is “literally slash followed by literally r”.
If you just did \r
, which the compiler would be happy with and turn into “backslash followed by carriage return”, the regex engine would then be looking for a “backslash followed by carriage return” not “backslash followed by r”
If you just did \r
the compiler would turn this into “backslash followed by r` but the regex engine would then interpret this as “looking for a carriage return”, when you’re “looking for slash then r”
Or
Regex.Match("blabla rn1.1 Entrepreneurship und Untern", @"\r\nd.ds");
For the same reasons: using an @ string stops the compiler transforming \
to and
r
to (a carriage return character) but you still have ta similar transformation carried out by the regex engine when it is interpreting. You need to make sure the regex engine sees \r
before it does its interpretation. If it sees r
or (a carraige return) it will be looking for a carriage return when you are looking for “slash then r”
Final footnote: regexstorm.net uses the .NET regex engine and is often a better test site than non-.net regex engine based sites, when you’re developing C# regexes
Read more here: Source link