Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx to read multiple parameters of unknown multiplicity

Tags:

java

regex

I'm a little stuck at a regular expression. Consider following code:

    String regFlagMulti = "^(\\[([\\w=]*?)\\])*?$";
    String flagMulti = "[TestFlag=1000][TestFlagSecond=1000]";
    Matcher mFlagMulti = Pattern.compile(regFlagMulti).matcher(flagMulti);

    if(mFlagMulti.matches()){
        for(int i = 0; i <= mFlagMulti.groupCount(); i++){
            System.out.println(mFlagMulti.group(i));
        }
    }else{
        System.out.println("MultiFlag didn't match!");
    }

What I want is a regular pattern that gives me the text inside the [ ]; each one in a group of the resulting Matcher object.

Important: I don't know how many [ ] expressions are inside the input string!

For the code above it outputs:

[TestFlag=1000][TestFlagSecond=1000]
[TestFlagSecond=1000]
TestFlagSecond=1000

I can't get the regular Pattern to work. Anyone an idea?

like image 806
Gruber Avatar asked May 26 '11 13:05

Gruber


1 Answers

What i want is a regular pattern that gives me the text inside the [ ]; each one in a group of the resulting Matcher object.

Unfortunately this can't be done with the Java regex engine. See my (similar) question over here:

  • Regular expression with variable number of groups?

This group:

(\\[([\\w=]*?)\\])*
\________________/

is group number 1 and will always contain the last match for that group.


Here's a suggestion for a solution, that also fetches the key/vals:

String regFlagMulti = "(\\[(\\w*?)=(.*?)\\])";
String flagMulti = "[TestFlag=1000][TestFlagSecond=1000]";
Matcher mFlagMulti = Pattern.compile(regFlagMulti).matcher(flagMulti);

while (mFlagMulti.find()) {
    System.out.println("String: " + mFlagMulti.group(1));
    System.out.println("   key: " + mFlagMulti.group(2));
    System.out.println("   val: " + mFlagMulti.group(3));
    System.out.println();
}

Output:

String: [TestFlag=1000]
   key: TestFlag
   val: 1000

String: [TestFlagSecond=1000]
   key: TestFlagSecond
   val: 1000
like image 133
aioobe Avatar answered Oct 12 '22 22:10

aioobe