Regex does not give the expected result.

The 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 Result:

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

But I got a way out:

 Shyam and you Ram and you 

Please correct me.

+4
source share
2 answers

You do not get contiguous matches because you match the ".\\s" next pattern in the previous pattern. Thus, they will no longer be matched.

You should use look-arounds:

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

Look-arounds is a statement of length 0. They will not use characters, but just check if the pattern is there or not, either forward or backward.


Literature:

+6
source

I'm not regexpert, but it looks like your template matches two. When there is only one between each sentence.

0
source

Source: https://habr.com/ru/post/1499009/


All Articles