简体   繁体   English

正则表达式没有给出预期的输出

[英]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. 请指正。

You are not getting adjacent matches, because you are matching the ".\\\\s" of the next pattern in the previous pattern. 您没有获得相邻匹配,因为您匹配上一个模式中下一个模式的".\\\\s" So, they won't be matched again. 所以,他们不会再次匹配。

You should use look-arounds: 你应该使用环视:

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

Look-arounds are 0-length assertion. 环视是0长度的断言。 They won't consume the characters, but just check whether a pattern is there or not, either forward, or backward. 它们不会消耗字符,而只是检查模式是否存在,无论是向前还是向后。


References: 参考文献:

我不是regexpert,但看起来你的模式与两个匹配。当每个句子之间只有一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM