What is wrong with matcher.find ()?

String s = "1.01"; Matcher matcher = Pattern.compile("[+-/\\*\\^\\%]").matcher(s); if (matcher.find()) { System.out.println(matcher.group()); } 

The input string is "1.01" and the output is ".". I can’t understand why matcher.find () returns true, there are no characters like "+", "-", "*", "^", "%" in the input line. Why did this happen?

+7
source share
2 answers

A dash in any position other than the first or last in the character class denotes a range of characters, just as [az] matches each lowercase letter from a to z, but [-az] matches only dashes, a and g. If you look at http : //www.asciitable.com/ , you will see that [+-/] will match any of +,-./

In addition, you do not need to avoid these characters in the regular expression, especially in the character class. As mentioned earlier, the main problem is the position of the dash in the character class.

You can fix your regular expression from

 "[+-/\\*\\^\\%]" 

to

 "[-+/\\*\\^\\%]" ^^ 

or without unnecessary shielding:

 "[-+/*^%]" 
+6
source

I'm sure you need to run. - Used as a range character in character classes such as [0-9] . - Must be escaped if you want to find dash examples.

If you change the order of the characters inside, you can leave with the whole pattern without any escapes. [-+*^%] should work and is a little easier to read.

+6
source

All Articles