【问题标题】:Simple Java regex matcher not working简单的 Java 正则表达式匹配器不起作用
【发布时间】:2021-05-06 12:18:40
【问题描述】:

代码:

import java.util.regex.*;

public class eq {
    public static void main(String []args) {
        String str1 = "some=String&Here&modelId=324";
        Pattern rex = Pattern.compile(".*modelId=([0-9]+).*");
        Matcher m = rex.matcher(str1);
        System.out.println("id = " + m.group(1));
    }
}

错误:

Exception in thread "main" java.lang.IllegalStateException: No match found

我在这里做错了什么?

【问题讨论】:

    标签: java regex


    【解决方案1】:

    您需要先在Matcher 上调用find(),然后才能调用group() 以及查询匹配文本或对其进行操作的相关函数(start()end()appendReplacement(StringBuffer sb, String replacement) 等) .

    所以在你的情况下:

    if (m.find()) {
        System.out.println("id = " + m.group(1));
    }
    

    这将找到 first 匹配项(如果有)并提取与正则表达式匹配的第一个捕获组。如果要在输入字符串中查找所有匹配项,请将 if 更改为 while 循环。

    【讨论】:

      【解决方案2】:

      您必须在调用group()之前添加此行:

      m.find();
      

      这会将指针移动到下一个匹配项的开头(如果有) - 如果找到匹配项,则该方法返回 true。

      通常,这是你使用它的方式:

      if (m.find()) {
          // access groups found. 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-16
        • 1970-01-01
        • 2019-05-28
        相关资源
        最近更新 更多