Java regex does not match as expected -
i'm starting regex in java recently, , cant wrap head around problem.
pattern p = pattern.compile("[^a-z]+"); matcher matcher = p.matcher("gets"); if (matcher.matches()) { system.out.println("matched."); } else { system.out.println("did not match."); }
result: did not match(unexpected result) explain this
i output "did not match." strange me, while reading https://docs.oracle.com/javase/7/docs/api/java/util/regex/pattern.html, i'm using x+, matches "one, or more times".
i thought code in words go this:
"check if there 1 or more characters in string "gets" not belong in z."
so i'm expecting following result:
"yes, there 1 character not belong a-z in "gets", regex match."
however not case, i'm confused why is. tried following:
pattern p = pattern.compile("[a-z]+"); matcher matcher = p.matcher("gets"); if (matcher.matches()) { system.out.println("matched."); } else { system.out.println("did not match."); }
result: did not match. (expected result)
pattern p = pattern.compile("[a-z]+"); matcher matcher = p.matcher("get"); if (matcher.matches()) { system.out.println("matched."); } else { system.out.println("did not match."); }
result: matched. (expected result)
please, explain why first example did not work.
matcher.matches
returnstrue
if entire region matches pattern.for output looking for, use
matches.find
instead
explanation of each case:
pattern p = pattern.compile("[^a-z]+"); matcher matcher = p.matcher("gets"); if (matcher.matches()) {
fails because the entire region 'gets'
isn't lowercase
pattern p = pattern.compile("[a-z]+"); matcher matcher = p.matcher("gets"); if (matcher.matches()) {
this fails because the entire region 'gets'
isn't uppercase
pattern p = pattern.compile("[a-z]+"); matcher matcher = p.matcher("get"); if (matcher.matches()) {
the entire region 'get'
uppercase, pattern matches.
Comments
Post a Comment