subbu lakshmi :
I am getting started with lookarounds in regex
I thought that the regex is a positive lookahead for a q 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?
munHunger :
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
. i.e 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());