staples
staples

Reputation: 424

Java Regex Issue when regex is correct

I have a regex that is correct, yet it fails in my program. Often a different set of eyes is good.

Relevant Code:

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);

Output

<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

I expect to finally see m_FAR_Gen_ParmFile as my o_mapping output.

When I test at this site: http://www.regexplanet.com/advanced/java/index.html, All passes and all is well. Why does it fail in my program? and how do I fix it?

Upvotes: 0

Views: 196

Answers (1)

Keppil
Keppil

Reputation: 46209

You need to call find() before 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);

From the Matcher#group() Javadoc:

Throws:
IllegalStateException - If no match has yet been attempted, or if the previous match operation failed

Upvotes: 5

Related Questions