正则表达式贪婪的问题

Mat*_*t P 3 regex regex-greedy

我确信这个很容易,但我尝试了很多变化,但仍然无法满足我的需要.事情太贪婪了,我不能让它停止贪婪.

鉴于案文:

test=this=that=more text follows
Run Code Online (Sandbox Code Playgroud)

我想选择:

test=
Run Code Online (Sandbox Code Playgroud)

我试过以下正则表达式

(\S+)=(\S.*)
(\S+)?=
[^=]{1}
...
Run Code Online (Sandbox Code Playgroud)

谢谢大家.

Owe*_*wen 11

这里:

// matches "test=, test"
(\S+?)=

or

// matches "test=, test" too
(\S[^=]+)=
Run Code Online (Sandbox Code Playgroud)

你应该考虑使用第一个版本.给定您的字符串"test=this=that=more text follows",版本1将匹配,test=this=that=然后继续解析到字符串的末尾.然后它会回溯,发现test=this=,继续回溯,找到test=,继续回溯,并test=作为最终答案来解决.

版本2将匹配test=然后停止.您可以在较大的搜索中看到效率提升,例如多行或整个文档匹配.