Exception in thread "main" java.lang.IllegalStateException: No match found at java.util.regex.Matcher.group (Unknown Source)

1

From the line

D:\csv\rssi_data_upload_00_11_74_86_49_7F_1519231770

I need to execute the regular expression

upload_(.+)_[0-9]+

to obtain the value of 00_11_74_86_49_7F .

This is my code:

public static void main(String[] args) throws FileNotFoundException
{

  String query_MAC_AP="upload_(.+)_[0-9]+";
  Pattern pmacap = Pattern.compile(query_MAC_AP);
  Matcher mmacap=pmacap.matcher("D:\csv\rssi_data_upload_00_11_74_86_49_7F_1519231770");
  mmacap.matches();
  String mac_AP=mmacap.group(1);
  System.out.println(mac_AP);
}

Every time I run it I get the following error

Exception in thread "main" java.lang.IllegalStateException: No match found
at java.util.regex.Matcher.group(Unknown Source)
at tfc.Main.main(Main.java:30)

What have I got wrong?

    
asked by Javi Gomez 11.03.2018 в 06:48
source

1 answer

2
  

java.lang.IllegalStateException: No match found at java.util.regex.Matcher.group

It is an error that occurs because:

  • The regex does not match
  • Then you're trying to reference Matcher#group() , the text captured by a match that does not exist!

Why does not it match?

Because the method Matcher # matches try to match ALL the text (the text from beginning to end), and clearly this is not the case with your regex ... In addition, you should always use a if / while to see if it coincided before referencing the result of a match.


To execute a regex on any position of a text the method is used Matcher # find () .

import java.util.regex.Matcher;
import java.util.regex.Pattern;
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

// Buscar la primera coincidencia del regex
// (o usar un while para buscar todas)

if (matcher.find()) {
    System.out.println("Coincide con: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Grupo " + i + ": " + matcher.group(i));
    }
}


You should always use Matcher#find() and forget matches() . To find a match in the whole text with find() , simply anchor it to ^ and $ (or actually to \A and \z ).

    
answered by 11.03.2018 / 06:50
source