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
What you’re looking for is
\G: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.