正则表达式仅第一次出现? [英] Regex to first occurrence only?
问题描述
假设我有以下字符串:
这是为了测试测试.这只是一个测试.结束.
this is a test for the sake of testing. this is only a test. The end.
我想选择this is a test
和this is only a test
.我到底需要做什么?
and I want to select this is a test
and this is only a test
. What in the world do I need to do?
我尝试的以下正则表达式产生了一个愚蠢的结果:
The following Regex I tried yields a goofy result:
this(.*)test
(我也想捕获它之间的内容)
this(.*)test
(I also wanted to capture what was between it)
returns 这是为了测试而测试.这只是一个测试
这似乎很容易让我忘记.
It seems like this is probably something easy I'm forgetting.
推荐答案
正则表达式是贪婪的,这意味着它会捕获尽可能多的属于 .*
匹配的字符.使其非贪婪尝试:
The regex is greedy meaning it will capture as many characters as it can which fall into the .*
match. To make it non-greedy try:
this(.*?)test
?
修饰符将使其在匹配中捕获尽可能少的字符.
The ?
modifier will make it capture as few characters as possible in the match.
这篇关于正则表达式仅第一次出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!