2017-03-02 69 views
3

例子:https://regex101.com/r/n4x91E/1如何匹配第一组发生与正则表达式?

输入字符串:

“我认为我们必须指出某些事情了这名男子,并在该点之后其他一些东西出来给他,以及”

我的正则表达式:

(point).*(out) 

RETURNING w ^荣结果:

“我认为我们必须point certain things out to this man, and after that point some other things out他还有”

预期结果:

“我认为我们必须point certain things out这个人,这一点其他一些后东西了他也是如此“

如何更改我的正则表达式以获得第一组的发生?

回答

1

你可以试试这个:

(point).*?(out) 

如果你只想要第一次出现的话就不要用全局标志......它只匹配第一次出现。请参阅以下链接。否则,你可以把全局标志 'G'

Explanation

1

充分利用正则表达式不贪心:

(point.*?out) 

示例代码:

String line = "I think we have to point certain things out to this man, and after that point some other things out to him as well"; 
String pattern = ".*(point.*?out).*"; 
Pattern r = Pattern.compile(pattern); 
Matcher m = r.matcher(line); 
if (m.find()) { 
    System.out.println(m.group(1)); 
    System.out.println(m.group(2)); 
} 

输出:

point certain things out 
point some other things out