1

Using example code on SO I found, and a string I'm searching, I'm trying to capture groups of aircraft classes and their seats. The input file has the aircraft configuration in the form J28W36Y156 which means 28 J (business) class seats, 36 W (premium economy seats) and 156 Y (economy) seats.

The Java code I'm using is as follows:

    s = "J12W28Y156";
    patternStr = "(\\w\\d+)+";
    p = Pattern.compile(patternStr);
    m = p.matcher(s);
    if (m.find()) {
        int count = m.groupCount();
        System.out.println("group count is "+count);
        for(int i=1;i<=count;i++){
            System.out.println(m.group(i));
        }
    }

The regex seems to only capture the LAST class seat config ie. Y156. How do I get this regex to capture all of the class/seat combos in multiple groups. Does this have something to do with it being a 'greedy' match I need to specifiy? I would like the output to be something like an array eg.

{J12, W28, Y156}

Thanks guys.

1 Answer 1

6

Your first mistake is a wrong interpretation of \w. Here is what javadoc says:

\w A word character: [a-zA-Z_0-9]

It means that \w captures both letters and digits. So, in your case taking in consideration that letters are always in upper case I'd use the following pattern:

[A-Z]\d+

Now it will capture the first place marker. So you should implement the loop yourself:

Pattern p = Pattern.compile("([A-Z]\\d+)");
Matcher m = p.matcher(str);
while (m.find()) {
    String place = m.group(1);
    // A12, W28 etc is here
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thankyou AlexR - I misunderstood the \w pattern...works perfectly now, thanks again.
Actually, the real problem with the regex is the final plus sign. "(\\w\\d+)+" captures J12 in group #1, then it captures W28 in group #1 (overwriting the J12), then it overwrites that with Y156. The reason your code works is because you removed the final plus sign from the regex AND used while (find()) to iterate over the matches. The \w was incorrect, but it wasn't causing the problem--it wasn't even a contributing factor. :-/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.