0

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?

6
  • 2
    We can't reproduce this without knowing line. Please show a short but complete program demonstrating the problem - and explain what you expected to see vs what you actually saw. Commented Sep 10, 2014 at 20:09
  • I have given you line check the output. If you follow my SysOuts, you have everything relevant Commented Sep 10, 2014 at 20:13
  • @staples I don't see it. Mind posting it as part of the code ? Commented Sep 10, 2014 at 20:16
  • 1
    @staples: Ah... that wasn't clear, and reading a question shouldn't be a detective story in itself. Why not just produce a short but complete program we can run? Commented Sep 10, 2014 at 20:22
  • Sorry about being unclear. -- where is a good place I could produce a short complete program online to post? Commented Sep 10, 2014 at 20:23

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.