Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match regex at start index?

Tags:

c#

.net

regex

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
like image 957
user541686 Avatar asked Nov 20 '11 06:11

user541686


People also ask

How do I match a regex pattern?

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 "(" .

How do I specify start and end in regex?

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.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

What is start in regex?

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.


1 Answers

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.

like image 94
Alan Moore Avatar answered Oct 15 '22 03:10

Alan Moore