简体   繁体   English

当str为点(“。”)时,如何获取Pattern.matches(regex,str)返回false?

[英]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 ("."). 我正在使用matchs方法根据正则表达式检查字符,但是在检查仅包含点(“。”)的字符串时,它始终返回true。 Here's the code: 这是代码:

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

This prints "BAD". 打印“ 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. 不,您调用的String matches不被视为正则表达式。 It is taken literally. 从字面上看。

Your case is printing BAD , because this [*+-/] is a character class where . 您的情况是打印BAD ,因为此[*+-/]是一个字符类,其中. 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. 尝试使用regexr,它色彩缤纷,在侧边栏上也有帮助,您可以在需要和不希望匹配的所有情况下更好地编写正则表达式。

To get you started, check out the really rudimentary regex written here: http://regexr.com/3af78 . 要开始使用,请查看此处编写的真正的基本正则表达式: 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. 由于我不知道您希望检查的严格程度或宽松程度,因此我添加了您可能会或可能不会考虑的其他字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM