[英]check if a string only contains specified characters
I want to check that a string only contains letters, a-zA-Z
, numbers 0-9
, and operators (+=-*/^)
我想检查一个字符串只包含字母, a-zA-Z
,数字0-9
和运算符(+=-*/^)
For example, the following expression would be permissible: 3 + 5(x^2)
例如,以下表达式是允许的: 3 + 5(x^2)
For example, the following expression would not be permissible: 3 $+ 5(x^2)
例如,下面的表达式将不容许: 3 $+ 5(x^2)
Would I use the matches function to do this? 我会使用匹配功能来执行此操作吗?
I tried: 我试过了:
// contains only operators, numbers, or letters
if(!exp.matches("[(+=-*/^)a-zA-Z0-9]")) {
return false;
}
I also tried escaping the asterisk, but it didn't work. 我也试过逃避星号,但它没有用。
You should have escaped -
or put it at the start/end of the character class, else it creates a range . 您应该已经转义-
或者将其放在角色类的开头/结尾,否则它会创建一个范围 。 Note that [=-*]
range is invalid : 请注意, [=-*]
范围无效 :
Also, you need a quantifier, +
to match 1 or more chars, *
to match 0 or more. 此外,您需要一个量词, +
匹配1个或多个字符, *
匹配0或更多。
Use 采用
if(!exp.matches("[a-zA-Z0-9+=*/^()-]+")) {
return false;
}
If you do not need to match (
and )
, remove them from the character class. 如果您不需要匹配(
和)
,请从字符类中删除它们。
Also, since the String#matches()
requires a full string match, no anchors at the start and end of the regular expression are necessary. 此外,由于String#matches()
需要完整的字符串匹配,因此不需要在正则表达式的开头和结尾处使用锚点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.