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?
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With