当正则表达式正确时,Java Regex问题

sta*_*les 0 java regex

我有一个正确的正则表达式,但它在我的程序中失败了.通常一组不同的眼睛是好的.

相关守则:

String s_mapping = ".*<MAPPING DESCRIPTION.*NAME =.*";
Pattern mapName = Pattern.compile("\"(m_.*?)\"");
String o_mapping = "";

...

if (line.matches(s_mapping)){
                Matcher matcher = mapName.matcher(line);
                System.out.println(line);
                System.out.println(matcher);
                o_mapping = matcher.group(1);
                System.out.println(o_mapping);
Run Code Online (Sandbox Code Playgroud)

产量

<MAPPING DESCRIPTION ="Mapping to generate the parameters file based on the parameters inserted in the table." ISVALID ="YES" NAME ="m_FAR_Gen_ParmFile" OBJECTVERSION ="1" VERSIONNUMBER ="2">
java.util.regex.Matcher[pattern="(m_.*?)" region=0,195 lastmatch=]
Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: No match found
Run Code Online (Sandbox Code Playgroud)

我希望最终看到m_FAR_Gen_ParmFile我的o_mapping输出.

当我在这个网站上测试时:http://www.regexplanet.com/advanced/java/index.html,所有通行证都很顺利.为什么我的程序失败了?以及如何解决?

Kep*_*pil 5

你需要调用find()之前group():

if (line.matches(s_mapping)){
    Matcher matcher = mapName.matcher(line);
    System.out.println(line);
    System.out.println(matcher);
    matcher.find();
    o_mapping = matcher.group(1);
    System.out.println(o_mapping);
Run Code Online (Sandbox Code Playgroud)

来自Matcher#group()Javadoc:

抛出:
IllegalStateException - 如果尚未尝试匹配,或者上一个匹配操作失败