2

I have a String that is something like this:

A20130122.0000+0000-0015+0000_name

Then I would like to extract this information:

The 20130122.0000+0000-0015+0000 that will be parsed to a date later on. And the final part which is name.

So I am using in Java something like this:

String regexpOfdate = "[0-9]{8}\\.[0-9]{4}\\+[0-9]{4}-[0-9]{4}\\+[0-9]{4}";
String regexpOfName = "\\w+";
Pattern p = Pattern.compile(String.format("A(%s)_(%s)", regexpOfdate, regexpOfName));
Matcher m = p.matcher(theString);
String date = m.group(0);
String name = m.group(1);

But I am getting a java.lang.IllegalStateException: No match found

Do you know what I am doing wrong?

Manuelarte
  • 1,658
  • 2
  • 28
  • 47

2 Answers2

3

You aren't calling Matcher#find or Matcher#matches methods after this line:

Matcher m = p.matcher(theString);

Try this code:

Matcher m = p.matcher(theString);
if (m.find()) {
    String date = m.group(1);
    String name = m.group(2);
    System.out.println("Date: " + date + ", name: " + name);
}
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Thanks, but it is working using this `String date = m.group(1); String name = m.group(2);` – Manuelarte Jan 22 '14 at 11:00
  • 1
    According to the JavaDoc for find() method: Attempts to find the next subsequence of the input sequence that matches the pattern. This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match. If the match succeeds then more information can be obtained via the start, end, and group methods. @return true if, and only if, a subsequence of the input sequence matches this matcher's pattern. So you need to call find(). – Tech Enthusiast Jan 22 '14 at 12:08
1

Matcher#group will throw IllegalStateException if the matcher's regex hasn't yet been applied to its target text, or if the previous application was not successful.

Matcher#find applies the matcher's regex to the current region of the matcher's target text, returning a Boolean indicating whether a match is found.

Refer

You can try this :

    String theString="A20130122.0000+0000-0015+0000_name";
    String regexpOfdate = "([0-9]{8})\\.[0-9]{4}\\+[0-9]{4}-[0-9]{4}\\+[0-9]{4}";
    String regexpOfName = "(\\w+)";
    Pattern p = Pattern.compile(String.format("A(%s)_(%s)", regexpOfdate, regexpOfName));
    Matcher m = p.matcher(theString);
    if(m.find()){
      String date = m.group(2);
      String name = m.group(3);
      System.out.println("date: "+date);
      System.out.println("name: "+name);
    }

OUTPUT

date: 20130122
name: name

Refer Grouping in REGEX

Community
  • 1
  • 1
Sujith PS
  • 4,776
  • 3
  • 34
  • 61