简体   繁体   English

使用负前瞻正则表达式的Java输入检查

[英]Java input check using negative lookahead regex

I am trying to using a regex negative lookahead to check if any invalid characters have been entered. 我正在尝试使用正则表达式否定先行检查是否输入了任何无效字符。 The characters I want to check for are everything but 0-9, whitespace, *, /, +, -, r, x. 我要检查的字符是除0-9,空格,*,/,+,-,r,x以外的所有字符。

String word = "(l4+3q)*(5+7-8)/(5)";
Pattern p  = Pattern.compile("(?![\\d\\srx*+-/)]+)");
Matcher m = p.matcher(word);

if(m.matches()) System.out.println("NO");

In this current test code, every string I use returns false. 在当前的测试代码中,我使用的每个字符串都返回false。

Could anyone provide me with some direction on how to modify this regular expression to work for my specifications. 谁能为我提供有关如何修改此正则表达式以使其符合我的规范的指导。

You don't want to use this +-/ in that order in the class. 您不想在课程中按此顺序使用此+-/
The - used this way is a range operator, not a literal -. -以这种方式使用的是范围运算符,而不是文字-。
To make it literal, add it to the end or beginning, or escape it 若要使其字面值,请将其添加到末尾或开头,或对其进行转义
and it can be anywhere. 它可以在任何地方。

Basically, you want to match anything not in that class. 基本上,你要在这个类匹配任何东西。
Pattern p = Pattern.compile("[^\\\\d\\\\srx*+\\\\-/)]");

If it matches if( m.matches() ) it did find an illegal character. 如果与if( m.matches() )相匹配, if( m.matches() )确实找到了非法字符。
or, 要么,
If it doesn't match if( !m.matches() ) it didn't find an illegal character. 如果不匹配if( !m.matches() )则找不到非法字符。

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

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