-1

I want to know why this regex group is not working for me in JAVA? It's throwing exception while finding match of group. I am trying to match the numbers separated by dashes.

Pattern p = Pattern.compile("([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)");
Matcher matcher = p.matcher("1-1-3-1-4");
matcher.group(0); // Exception happens here - java.lang.IllegalStateException: No match found
Pratik K. Shah
  • 397
  • 3
  • 17
  • No. Could you please point, if anything specific to take a look which is causing this issue? – Pratik K. Shah Jun 12 '17 at 03:05
  • Using `matcher()` doesn't actually try to match anything. It just sets the matcher up. You have to tell it to try a match with one of the [`Matcher` methods](http://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html). – ajb Jun 12 '17 at 03:05
  • 1
    use `matcher.find()` to iterate over all occurances. – jack jay Jun 12 '17 at 03:07
  • that's what he is doing by using `group` – f.khantsis Jun 12 '17 at 03:11
  • @f.khantsis [Have a look at this](https://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#group(int)) – jack jay Jun 12 '17 at 03:22

2 Answers2

4

You need to call Matcher#find() to actually get a match:

Pattern p = Pattern.compile("([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)");
Matcher matcher = p.matcher("1-1-3-1-4");
if (matcher.find()) {
    System.out.println(matcher.group(0))
}

If you were expecting multiple matches, you could use a while loop instead of an if statement.

Also note that you actually have five capture groups in your patterns. Capture groups are denoted by placing a portion of the pattern in parentheses. If you don't intend/need to capture the five separated numbers in your pattern individually, then you can consider telling the regex engine not to capture them, e.g. use this:

Pattern p = Pattern.compile("(?:[0-9]+)-(?:[0-9]+)-(?:[0-9]+)-(?:[0-9]+)-(?:[0-9]+)");

Demo

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

In Java regex index or study methods are used to return Matcher class matches:

if (matcher.matches()) {
    System.out.println(matcher.group(0));
}

In the example above, the matches() "study" method attempts to match the entire region against the given pattern. Which method you use is generally indicative of what/how you want to match.

matches()

Attempts to match the entire region against the pattern.

find()

Attempts to find the next subsequence of the input sequence that matches the pattern.

Study methods review the input string and return a Boolean indicating whether or not the pattern is found

http://docs.oracle.com/javase/tutorial/essential/regex/matcher.html

l'L'l
  • 44,951
  • 10
  • 95
  • 146