Skip to content
Advertisement

Java Pattern and Matcher no result

i’m writing this Java program for fun and i’m trying to get groups of substring with a regex. My string is read from a file and it’s something like:

t<firstName type="String">John</firstName>

where t is a tab.

I wrote this code to isolate the needed substring, but while on online testing it works, in my code it says “no matches”.

try {
    Pattern r = Pattern.compile(".+<(.+) type="(.+)">(.+)</(.+)>");
    Matcher m = r.matcher(line);

    String name = m.group(1);
    String type = m.group(2);
    String value = m.group(3);

    System.out.println(""" + line + "" matched regex");
    
} catch (Exception ex){
    System.out.println(""" + line + "" didn't match regex");
}

My output is:

"   <firstName type="String">John</firstName>" didn't match regex
"   <surname type="String">Doe</surname>" didn't match regex
"   <age type="int">18</age>" didn't match regex

Do you have any clue?

Advertisement

Answer

You’ve just created a matcher in this line: Matcher m = r.matcher(line). If you print the exception, you’ll see No match found message.

You are using m.group() without calling matches() method.

Try this:

try {

    Pattern r = Pattern.compile(".+<(.+) type=\"(.+)\">(.+)</(.+)>");
    Matcher m = r.matcher(line);
    if (m.matches()) {

        String name = m.group(1);
        String type = m.group(2);
        String value = m.group(3);
        System.out.println(""" + line + "" matched regex");
    }

} catch (Exception ex) {
    System.out.println(""" + line + "" didn't match regex");
}

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement