RegEx to read multiple parameters of unknown multiplicity
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 Match开发者_运维技巧er 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?
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
Use a pattern which matches a single item in the string and use Matcher.find()
to iterate over the whole String.
You can try the following:
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));
}
Output:
TestFlag=1000
TestFlagSecond=1000
As Aaron correctly pointed out, use one group (they are static to the pattern, repetitions are not added as additional groups) and call find
.
The pattern to use could be like this: \G\[([^\]]*)\](?=\[|$)
Group 1 will then contain the text inside the []
.
Notes:
\G
continues the match where the last match ended
(?=
is a positive lookahead to make sure that the end of the pattern is as expected (e.g. either the end of the string, or the next [
).
精彩评论