jeudi 8 octobre 2015

Java - How do I code optional regex patterns with a matcher

Let’s say I am looping through a text file and come across the following two strings with random words and integer values

“foo 11 25”
“foo 38 15 976 24”

I write a regex pattern that would match both strings, for example:

((?:[a-z][a-z]+)\\s+\\d+\\s\\d+)

But, the problem is I don’t think this regex would allow me to get to all 4 integer values in the 2nd string.

Q1.) How can I create a single pattern that leaves these 3rd and 4th integers optional?

Q2.) How do I write the matcher code to only go after the 3rd and 4th values when they are found by the pattern?

Here is a template program to help anyone willing to offer a hand. Thanks.

public void foo(String fooFile) {
        //Assume fooFile contains the two strings
        //"foo 11 25";
        //"foo 38 976 24";

        Pattern p = Pattern.compile("((?:[a-z][a-z]+)\\s+\\d+\\s\\d+)", Pattern.CASE_INSENSITIVE);

        BufferedReader br  = new BufferedReader(new FileReader(fooFile));
        String line;
        while ((line = br.readLine()) != null) {
            //Process the patterns
            Matcher m1 = p.matcher(line);
            if (m1.find()) {
                int int1, int2, int3, int4;
                //Need help to write the matcher code
            }
        }
    }

Aucun commentaire:

Enregistrer un commentaire