首页 > 解决方案 > 为什么lookArounds的lookAround返回true,而匹配返回false

问题描述

我开始使用正则表达式中的环视

我认为正则表达式是 aq 的积极前瞻,然后是 u。但是当输入字符串为“qu”时,它不匹配。但是我得到了 lookingAt 函数的真实结果。

String regex="q(?=u)";
Pattern p= Pattern.compile(regex);
String test = "qu";
Matcher m= p.matcher(test);
System.out.println(m.matches());
System.out.println(m.lookingAt());

谁能解释为什么会这样?

标签: javaregex-lookarounds

解决方案


我认为这是因为它试图匹配整个字符串

火柴()

尝试将整个区域与模式匹配。

并且具有积极的前瞻性,我认为它与u. 即q 如果它后面跟着一个u. 因此,这q不是整个测试字符串,也不匹配整个字符串。

这就是为什么你可以写这个来得到true

    String regex="^q(?=u)u";
    Pattern p= Pattern.compile(regex);
    String test = "qu";
    Matcher m= p.matcher(test);
    System.out.println(m.matches());
    System.out.println(m.lookingAt());

推荐阅读