samedi 30 avril 2016

Java regex pattern not working as intended

I am new to patterns and regex and have encountered a problem which I can't solve. This is my code:

public static void main(String[] args) {

    Pattern pattern = Pattern.compile("(!?)(fw|ri|le|cl|rs)[\\s,]*(\\d*\\.*\\d*|\"\\w*\")?[\\s,]*(\\d*\\.*\\d*|\"\\w*\")?[\\s,]*(\\d*\\.*\\d*|\"\\w*\")?");
    Matcher matcher = pattern.matcher("!fw 90.0 \"hello\" 70.0");

    matcher.find();
    for(int i = 0; i < matcher.groupCount()+1; i++) {
        System.out.println("Group "+i+") " + matcher.group(i));
    }
}

So, i've used regexr.com to create the regex, and on the website it works as planned. It should find 3 arguments which can be either a number or a String, where the String is enclosed in quotation mark. As I said, on regexr.com it works, however in java it does only, when there are no Strings. What am I doing wrong? (The regex without the extra backslashes is (!?)(fw|ri|le|cl|rs)[\s,]*(\d*\.*\d*|"\w*")?[\s,]*(\d*\.*\d*|"\w*")?[\s,]*(\d*\.*\d*|"\w*")? )

Thanks in advance.

Edit: Some examples of what does happen and what doesn't:

Working as intended:

Input: !fw 1.0 2.0 3.0

Ouput: Group 0) !fw 1.0 2.0 3.0 Group 1) ! Group 2) fw Group 3) 1.0 Group 4) 2.0 Group 5) 3.0

Not working as intended:

Input: !fw 1.0 \"hello\" 3.0

Output: Group 0) !fw 1.0 Group 1) ! Group 2) fw Group 3) 1.0 Group 4) Group 5)

Intended Output: Group 0) !fw 1.0 "hello" 3.0 Group 1) ! Group 2) fw Group 3) 1.0 Group 4) "hello" Group 5) 3.0

Aucun commentaire:

Enregistrer un commentaire