如何在Java中使用Regex进行模式匹配? [英] How to use Regex in Java to pattern match?

查看:125
本文介绍了如何在Java中使用Regex进行模式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在线阅读了文档和各种教程,但我仍然对regex在Java中的工作原理感到困惑。我要做的是创建一个接受类型字符串参数的函数。然后我想检查传递的字符串是否包含
MDCLXVIivxlcdm以外的任何字符。因此,例如,字符串XMLVID​​应返回false,ABXMLVA应返回true。

I have read the documentation and various tutorials online but I'm still confused on how regex works in Java. What I am trying to do is create a function which takes in argument of type string. I then want to check if the passed string contains any characters other than MDCLXVIivxlcdm. So for example, string "XMLVID" should return false and "ABXMLVA" should return 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;
 }

当我通过时,XMLIVD,ABXMLVA和XMLABCIX ,都归还假。我究竟做错了什么?任何帮助将不胜感激。

When I pass, "XMLIVD", "ABXMLVA", and "XMLABCIX", all return false. What am I doing wrong? Any help will be greatly appreciated.

推荐答案

您需要使用字符类中的Java字符类交集运算符,否则字面匹配&安培;&安培; 。顺便说一下,你的第一个字符类从 A 到(小写) z 还包括 [\ ] ^ _ ,你当然不想要;而且你拼错了Patter.complile。

You will need to use Java's character class intersection operator inside a character class, otherwise it literally matches &&. Btw, your first character class from A to (lowercase) z also includes [\]^_, which you certainly do not want; and you misspelled "Patter.complile".

另外, matches()


尝试将整个区域与模式匹配。

所以你需要使用 find()或者用填充表达式。*

So you either need to use find() instead or pad the expression with .*.

public boolean checkString(String arg) {
    return Pattern.compile("[[a-zA-Z]&&[^MDCLXVIivxlcdm]]").matcher(arg).find();
}

这篇关于如何在Java中使用Regex进行模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆