【问题标题】:How to use Regex in Java to pattern match?如何在 Java 中使用 Regex 进行模式匹配?
【发布时间】:2013-01-29 12:21:22
【问题描述】:

我已经在线阅读了文档和各种教程,但我仍然对正则表达式在 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;
 }

当我通过时,“XMLIVD”、“ABXMLVA”和“XMLABCIX”都返回 false。我究竟做错了什么?任何帮助将不胜感激。

【问题讨论】:

    标签: java regex string string-matching


    【解决方案1】:

    您需要在字符类中使用Java's character class 交集运算符,否则它与&& 匹配。顺便说一句,你从A 到(小写)z 的第一个字符类还包括[\]^_,这是你肯定不想要的;你拼错了“Patter.complile”。

    另外,matches()

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

    因此,您要么需要改用find(),要么使用.* 填充表达式。

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

    【讨论】:

    • 我试过了,但结果是一样的。当我通过“XMLIVD”、“ABXMLVA”和“XMLABCIX”时都返回 false。但它应该返回 false、true、true。
    • 感谢 find 方法有效。因此,或者我可以这样做 [[.*a-zA-Z.*]&&[^MDCLXVIivxlcdm]]?
    • 不,我是说Pattern.compile(".*[[a-zA-Z]&&[^MDCLXVIivxlcdm]].*").matcher(arg).matches();
    【解决方案2】:

    你可以使用这样的函数,有两个参数,即,

    • origingalString要检查的原始字符串
    • searchString要搜索的字符串

    代码准确,

    public boolean checkCompletelyExist(String origingalString,String searchString){ 
      boolean found = false; 
      String regex = ""; 
      try{ 
        for(int i = 0; i < searchString.length();i++){ 
          String temp = String.valueOf(searchString.charAt(i)); 
          regex = "[\\x20-\\x7E]*"+"["+temp.toLowerCase()+"|"+temp.toUpperCase()+"]+[\\x20-\\x7E]*"; 
          if(!origingalString.matches(regex)){ 
            found = true; 
            break; 
          } 
        } 
        System.out.println("other character present : "+found); 
      } catch (Exception e) { 
        e.printStackTrace(); 
      } 
      return found; 
    }
    

    例如:

    checkCompletelyExist("MDCLXVIivxlcdm","XMLVID") 输出将是 other character present : false

    checkCompletelyExist("MDCLXVIivxlcdm","ABXMLVA") 输出将是other character present : true

    【讨论】:

    • 如果你使用 eclipse ctrl+I 是为了缩进。没有时间绘图。如果你想要一个解决方案并打算使用 urslf。 :)。感谢您提供的链接。
    • 不,您也可以并且应该在 StackOverflow 上进行缩进。如果 eclipse 自动缩进您的代码,请发布。无需在任何地方手动插入&lt;br&gt;s
    • 好的,先生,我会的……我对这里完全陌生……谢谢你的建议……下次我会关心的,
    【解决方案3】:

    Regular Expressions (RegEx / RegExp) 基本上,正则表达式是描述一定数量文本的模式。

    ^abc$   start / end of the string
    \b \B   word, not-word boundary
    \w \d \s    word, digit, whitespace
    \W \D \S    not word, digit, whitespace
    \z  - End of entire string
    (…) - Grouping (capture groups)
    [abc]   any of a, b, or c
    [^abc]  not a, b, or c
    [a-g]   character between a & g
    { m,n } - quantifiers for “from m to n repetitions”
    + - quantifiers for 1 or more repetitions (i.e, {1,})
    ? - quantifiers for 0 or 1 repetitions (i.e, {0,1})
    

    POSIX Bracket Expressions POSIX 括号表达式是一种特殊的字符类。 POSIX 括号表达式匹配一组字符中的一个字符,就像常规字符类一样。 POSIX 字符类名称必须全部小写。 POSIX 标准定义了 12 个字符类。下表列出了所有 12 个类,以及一些正则表达式也支持的 [:ascii:][:word:] 类。

    模式匹配with正则表达式:

    final Pattern mix_alphaNumaric_pattern = Pattern.compile("^[A-Za-z0-9]+$");
    final Pattern alphabets_pattern = Pattern.compile("^[A-Za-z,\\- ]+$");
    final Pattern alphabetsNull_pattern = Pattern.compile("|^[A-Za-z,\\- ]+$");
    final Pattern numaric_pattern = Pattern.compile("^[0-9]+$");    // ^begning +followed By $end
    final Pattern date_time_pattern = Pattern.compile("\\d{1,2}/\\d{1,2}/\\d{4}\\s\\d{1,2}\\:\\d{1,2}");
    final Pattern weather_pattern = Pattern.compile("[\\-]*\\d{1,3}\\.\\d{1,6}");
    final Pattern email_pattern = Pattern.compile("^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$");
    final Pattern mobile_pattern = Pattern.compile("(\\+)?(\\d{1,2})?\\d{10}");
    
    public static void main(String[] args) {
        String[] str = {"MCDL", "XMLIVD", "ABXMLVA", "XMLABCIX"}; 
        Pattern p = Pattern.compile("^(M|D|C|L|X|V|I|i|v|x|l|c|d|m)+$");
        // Returns: true if, and only if, the entire region sequence matches this matcher's pattern
        for (String sequence : str ) {
            boolean match = false, find = false;
            if ( !p.matcher(sequence).matches() ) match = true;
            if (p.matcher(sequence).find())       find = true;
    
            System.out.format("%s \t Match[%s] Find[%s]\n", sequence, match, find);
        }
    }
    

    输出:

    MCDL     Match[false] Find[true]
    XMLIVD   Match[false] Find[true]
    ABXMLVA      Match[true] Find[false]
    XMLABCIX     Match[true] Find[false]
    

    @查看此链接:

    【讨论】:

      猜你喜欢
      • 2021-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多