Search code examples
javaregexuuid

Filtering out UUId number from a string


I want to filter out into a new string only the strings that has UUID number example:

02bfa116-c834-4896-b825-e8f1299319f9,8.1.0,2888F244914F75CD68DC70A11B71BF0420F,panos

Expected: getting a new string that will contain this value '02bfa116-c834-4896-b825-e8f1299319f9'

what I've tried so far:

final String regex = "[a-f0-9]{8}(-[a-f0-9]{4}){4}[a-f0-9]{8}";
        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        for(int i=0;i<arr.length;i++){
            Matcher matcher = pattern.matcher(arr[i]);
            contentCSVStr[i] = matcher.group();
        }

where each string inside the array could be in the format I gave in the example above.

when I run this code I am getting

java.lang.IllegalStateException: No match found

what am I missing?


Solution

  • You're forgetting the call to Matcher.find.

    Change your code to this:

    final String regex = "[a-f0-9]{8}(-[a-f0-9]{4}){4}[a-f0-9]{8}";
    final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
    for(int i=0;i<args.length;i++){
        Matcher matcher = pattern.matcher(args[i]);
        matcher.find(); // <- This line needed to be added
        contentCSVStr[i] = matcher.group();
    }
    

    And it will correctly extract the UUID.

    group returns the results of the previous match, but until you call find no match has happened yet, so it has no results to return.