简单的Java正则表达式匹配器无法正常工作 [英] Simple Java regex matcher not working

查看:131
本文介绍了简单的Java正则表达式匹配器无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

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

我在这里做错了什么?

推荐答案

你需要打电话给find() Matcher 上的,然后才能调用 group()以及查询匹配文本的相关函数或操纵它( start() end() appendReplacement(StringBuffer sb,String替换)等。)。

You need to call find() on the Matcher before you can call group() and related functions that queries about the matched text or manipulate it (start(), end(), appendReplacement(StringBuffer sb, String replacement), etc.).

所以在你的情况下:

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

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

This will find the first match (if any) and extract the first capturing group matched by the regex. Change if to while loop if you want to find all matches in the input string.

这篇关于简单的Java正则表达式匹配器无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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