Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
对不起。我重新调整了下面的示例,如何在下一段中第一次出现mary之后匹配数字( 1 ) (在我的情况下,所有三个组都是强制性的):
Regex.Match("Do you know 3453 **Mary** has a little lamb 1 and Mary likes dancing 2." , @"(Do).*(Mary).*(\d)");
目前它与第二个Mary匹配,结果第三组捕获了2而不是1
使用.*?代替.*:
.*?
.*
Regex.Match("Do you know **Mary** has a little lamb 1 and Mary likes dancing 2.", @"(Do).*?(Mary).*?(\d)");
.*匹配可能的最长子串(贪婪),而.*?匹配最短的(惰性)。在您的示例中,第一个.*包含第一个Mary,因为它匹配尽可能多的字符。
Mary