简体   繁体   中英

Why does lookingAt return true for lookArounds while matches return false

I am getting started with lookarounds in regex

I thought that the regex is a positive lookahead for aq followed by u. But when the input string is "qu" it isnt matched. But I get a true result for the lookingAt function.

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

Can anybody explain why this happens?

I assume that it is because it is trying to match the entire string

matches()

Attempts to match the entire region against the pattern.

And with a possitive lookahead I don't think that it matches the u . ie the match will be q if it is followed by a u . Thus the q is not the entire test string and it is not matching the entire string.

which is why you can write this to get 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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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