正则表达式组捕获,如何在下一个词之前停止

Regex Group Capture, how to stop before next word

我有以下正则表达式:

Defaults(.*)Class=\"(?<class>.*)\"(.*)StorePath=\"(?<storePath>.*)\"

以及以下字符串:

Defaults Class="Class name here" StorePath="Any store path here" SqlTable="SqlTableName"

我正在努力实现以下目标:

class Class name here
storePath Any store path here

但是,我得到的结果是:

class Class name here
storePath Any store path here SqlTable="SqlTableName"

如何在Sqltable文本前停止?

语言是 C#,正则表达式引擎是 .NET 框架内置的。

非常感谢!

@ahmed-abdelhameed提出的方案解决了问题,我忘记了非贪心

Defaults(.*)Class=\"(?<class>.*)\"(.*)StorePath=\"(?<storePath>.*?)\"

谢谢!

storePath 组中,您匹配任意字符零次或多次(贪婪匹配)。贪婪匹配的意思是它会 return 尽可能多的字符,所以它会一直匹配字符,直到它到达最后一次出现的 ".

您需要做的是将 .* 替换为 .*?,从而将贪婪匹配转换为惰性匹配。惰性匹配的意思是它会 return 尽可能少的字符,所以在你的情况下,它会一直匹配字符,直到它到达 ".

的第一次出现

只需将您的正则表达式替换为:

Defaults(.*)Class=\"(?<class>.*)\"(.*)StorePath=\"(?<storePath>.*?)\"

参考文献:

更容易阅读:

Class="(.+?)".+?StorePath="(.+?)"

.+?是说match non-greedy,基本上是尽量少匹配。 这将导致它捕获到下一个“