RegEx to read multiple parameters of unknown multiplicity

I am a bit stuck in regex. Consider the 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 template that gives me the text inside [] ; each of which is in the group of the resulting Matcher object.

Important: I do not know how many [] expressions are inside the input string!

For the code above, it produces:

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

I can not get the regular pattern to work. Any idea?

+5
source share
4 answers

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

, Java regex. . () :


:

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

- 1 .


, /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();
}

:

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

String: [TestFlagSecond=1000]
   key: TestFlagSecond
   val: 1000
+3

, , Matcher.find() .

+3

:

String regFlagMulti = "\\[(\\w+=.*?)\\]";
String flagMulti = "[TestFlag=1000][TestFlagSecond=1000]";
Matcher mFlagMulti = Pattern.compile(regFlagMulti).matcher(flagMulti);
while(mFlagMulti.find()){
    System.out.println(mFlagMulti.group(1));
}

:

TestFlag=1000
TestFlagSecond=1000
+3

, ( , ) find.

: \G\[([^\]]*)\](?=\[|$)

1 [].

:

\G ,

(?=is a positive result to ensure that the end of the pattern is as expected (for example, end of line or next [).

0
source

All Articles