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 returns true 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

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -