Sorry. I rephased the example as below, how can I match number ( 1 ) right after the first appearance of mary in the following paragraph ( all the three groups are mandatory in my case):
Regex.Match("Do you know 3453 **Mary** has a little lamb 1 and Mary likes dancing 2."
, @"(Do).*(Mary).*(\d)");
Currently It matches the second Mary , as a result, the third group captured 2 instead of 1
Use .*?
instead of .*
:
Regex.Match("Do you know **Mary** has a little lamb 1 and Mary likes dancing 2.",
@"(Do).*?(Mary).*?(\d)");
.*
matches the longest substring possible (greedy), while .*?
matches the shortest (lazy). In your example, the first .*
included the first Mary
because it matches as many characters as possible.
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.