简体   繁体   中英

How to get Pattern.matches(regex, str) to return false when str is dot (“.”)?

I would like to check if a string is a mathematical operator (+,-,*,/). I'm using the matches method to check the character against a regex but it always returns true when checking a string that contains only a dot ("."). Here's the code:

String dot = ".";
        if(dot.matches("[*+-/]"))
                System.out.println("BAD");
        else
                System.out.println("GOOD");

This prints "BAD". I get that it probably has to do with the fact that "." in regex matches everything but I don't see why that would make a difference. Is there any way to get this to return false? Thanks.

No, the String you invoke matches on is not considered a regular expression. It is taken literally.

Your case is printing BAD , because this [*+-/] is a character class where . falls between + and / . Move the - to the end so that it doesn't create a range, [*+/-] .

I'm going to suggest a tool for going about this.

Try regexr, it's colorful, it's got help on the sidebar, and you will be able to write regexes better with all the cases you want and do not want to match.

To get you started, check out the really rudimentary regex written here: http://regexr.com/3af78 .

\d [*+/-] \d

As I do not know how strict or loose you want your check to be, I've added additional strings that you may or may not want to consider.

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