简体   繁体   中英

How to match regex at start index?

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 :

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.

Ooooh I just remembered something I'd read ~4-5 years ago in a book regarding Regex.Match ...

The overloads don't behave the way we expect them to!

The overload

Regex.Match(string input, int index, int length)

specifies a substring to search, whereas the overload

Regex.Match(string input, int index)

merely dictates where the search should start !

(The one case it leaves out starting at an arbitrary position in a substring , I guess.)

Hope this is enlightening for people...

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