Nidhin Joseph
Nidhin Joseph

Reputation: 1481

Regex not giving the expected output

Code:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Regex {
public static void main(String[] args) {
    String data = ". Shyam and you. Lakshmi and you. Ram and you. Raju and you. ";
    Pattern pattern = Pattern.compile("\\.\\s(.*?and.*?)\\.\\s");
    Matcher matcher = pattern.matcher(data);
    while (matcher.find()) {
        System.out.println(matcher.group(1));
    }

}
}

Expected output:

Shyam and you
Lakshmi and you
Ram and you
Raju and you

But the output i got was:

Shyam and you
Ram and you

Please correct me.

Upvotes: 4

Views: 99

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213203

You are not getting adjacent matches, because you are matching the ".\\s" of the next pattern in the previous pattern. So, they won't be matched again.

You should use look-arounds:

Pattern.compile("(?<=\\.\\s)(.*?and.*?)(?=\\.\\s)");

Look-arounds are 0-length assertion. They won't consume the characters, but just check whether a pattern is there or not, either forward, or backward.


References:

Upvotes: 6

Eric Stein
Eric Stein

Reputation: 13672

I'm no regexpert, but It looks like your pattern is matching for two ., when there's only one in between each sentence.

Upvotes: 0

Related Questions