PAu*_*a03 3 java regex string string-matching
我已经在线阅读了文档和各种教程,但我仍然对正则表达式如何在Java中工作感到困惑.我要做的是创建一个接受类型字符串参数的函数.然后,我想检查传递的字符串是否包含除MDCLXVIivxlcdm之外的任何字符.因此,例如,字符串"XMLVID"应返回false,"ABXMLVA"应返回true.
public boolean checkString(String arg)
{
Pattern p = Pattern.complile("[a-zA-z]&&[^MDCLXVIivxlcdm]");
Matcher m = p.matcher(arg);
if(m.matches())
return true;
else
return false;
}
Run Code Online (Sandbox Code Playgroud)
当我通过时,"XMLIVD","ABXMLVA"和"XMLABCIX"都返回false.我究竟做错了什么?任何帮助将不胜感激.
您将需要在字符类中使用Java的字符类交集运算符,否则它将完全匹配&&.顺便说一下,你的第一个字符类A(小写)z也包括[\]^_,你当然不想要; 你拼错了"Patter.complile".
也, matches()
尝试将整个区域与模式匹配.
因此,您需要使用find()替代或填充表达式.*.
public boolean checkString(String arg) {
return Pattern.compile("[[a-zA-Z]&&[^MDCLXVIivxlcdm]]").matcher(arg).find();
}
Run Code Online (Sandbox Code Playgroud)