How do I create a regex that begins matching where it starts searching?
In other words:
What is the equivalent of \A
which says, "match at the start of the search, even if it's not in the beginning of the main string"?
new Regex(@"\A\n").IsMatch("!\n", 1); // Should be true, but is false
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" .
To match the start or the end of a line, we use the following anchors: Caret (^) matches the position before the first character in the string. Dollar ($) matches the position right after the last character in the string.
$ means "Match the end of the string" (the position after the last character in the string).
As usual, the regex engine starts at the first character: 7. The first token in the regular expression is ^. Since this token is a zero-length token, the engine does not try to match it with the character, but rather with the position before the character that the regex engine has reached so far.
What you're looking for is \G
:
new Regex(@"\G\n").IsMatch("!\n", 1); // It's twue, it's twue!
This was a surprise to me, actually. I knew about \G
, but it's usually described as an anchor that matches the beginning of the input or the end of the most recent successful match, neither of which applies here. If this is a .NET innovation, they should make more noise about it; it looks like it could be very handy.
EDIT: Come to think of it, Java's find(int)
does work the same way--I've even used it extensively. But then they added the "regions" API in Java 5, which offers much finer control, and I forgot about this idiom. I never thought to look for it in .NET.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With