0

I am simply trying to capture a string surrounded static text. I'll illustrate by example. Here is the string I'm working with ...

String idInfo = "Any text up here\n" +
                "Here is the id\n" +
                "\n" +
                "?a0 12 b5\n" +
                "&Edit Properties...\n" +
                "And any text down here";

Or in pretty print ...

Any text up here
Here is the id

?a0 12 b5
&Edit Properties...
And any text down here

And I'm using the following code to try and print the ID number ...

Pattern p = Pattern.compile("Here is the id\n\n\?[a-z0-9]{2}( [a-z0-9]{2}){2}\n&Edit Properties...);
Matcher m = p.matcher(idInfo);
String idNum = m.group(1);
System.out.println(idNum);

And I want to simply output the ID number, so the output I desire for this example is ...

a0 12 b5

However, I'm getting a "No match found" exception when I run my code. What am I doing wrong? Is there a simpler, more elegant way to accomplish my solution?

user2150250
  • 4,797
  • 11
  • 36
  • 44

1 Answers1

2

You need to let Matcher find match before you use it. So invoke m.find() (or m.matches() depending on your goal) before accessing m.group(1);. Also check if match was actually found (if m.find() retuned true) to make sure that group 1 exists.

Other thing is that string representing your regex is incorrect. If you want to escape ? in regex you need to write \ as two "\\" because \ is special character in String (used for instance to create \n) which also needs escaping.

Last thing you pointed yourself in comment is that ( [a-z0-9]{2}) wouldn't put match a0 12 b5 in group 1. To solve this problem we need to surround [a-z0-9]{2}( [a-z0-9]{2}){2} in parenthesis.

So try maybe

Pattern p = Pattern.compile("Here is the id\n\n\\?([a-z0-9]{2}( [a-z0-9]{2}){2})\n&Edit Properties...");
Matcher m = p.matcher(idInfo);

if (m.find()) {//or while(m.find())
    String idNum = m.group(1);
    System.out.println(idNum);
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • Your code is lacking the parentheses for the capture group around the ID too. Discovered that in testing. I believe it should be "Here is the id\n\n\\?([a-z0-9]{2}( [a-z0-9]{2}){2})\n&Edit Properties..." correct? – user2150250 Nov 07 '14 at 19:37
  • @user2150250 Yes, you are correct. I missed that my code wasn't returning output you described in your question. Fixed now. – Pshemo Nov 07 '14 at 19:51