6

Example: https://regex101.com/r/n4x91E/1

INPUT STRING :

"I think we have to point certain things out to this man, and after that point some other things out to him as well"

MY REGULAR EXPRESSION :

(point).*(out)

RETURNING WRONG RESULT :

"I think we have to point certain things out to this man, and after that point some other things out to him as well"

EXPECTING RESULT :

"I think we have to point certain things out to this man, and after that point some other things out to him as well"

How to change my regular expression to get the first groups occurrence ?

阿尔曼
  • 1,275
  • 2
  • 14
  • 18

3 Answers3

11

You can use a lazy quantifier for your regular expression like in this version:

https://regex101.com/r/n4x91E/2

(point).*?(out)

In the Java documentation this quantifier is called reluctant, but I think lazy is more commonly used...

dpr
  • 10,591
  • 3
  • 41
  • 71
1

You can try this:

(point).*?(out)

If you only want the first occurrence then don't use global flag... it only match the first occurrence . see the following link . Otherwise you can put the global flag 'g'

Explanation

Mustofa Rizwan
  • 10,215
  • 2
  • 28
  • 43
1

Make the regex non greedy:

(point.*?out)

Sample code:

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));
}

Output:

point certain things out
point some other things out
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360