Reputation: 1254
I have a string like that: obj[attr1=val1 attr2=val2 attr3=val3]
i need to extract object name and attributes.
Earlier, i've decided similar task in javascript using next regexp:
/^(\w+)(?:\[(\w+=\w+)(?:\s(\w+=\w+))*\])?$/
Now i have a trouble deciding in java:
Pattern pathPattern = Pattern.compile("^(\\w+)(?:\\[(\\w+=\\w+)(?:\\s+(\\w+=\\w+))*\\])?$");
I'm getting just a object name and first attribute. It seems that Mather class gets group count corresponding to count of "()" without considering symbol "*".
Is exists the possibility to make working java reg exp like js regexp, or i need to make two steps extraction?
thank you
Upvotes: 2
Views: 3816
Reputation: 213263
Matcher.groupCount()
only counts the number of opening-brackets and consider them to be a group. So, the number of brackets you open will be the number of group counts (provided you are not using any non-capturing group).
You can use the below pattern to get the value inside the [.*]
: -
Pattern pattern = Pattern.compile("(?:\\b)(\\w+?)=(\\w+?)(?:\\b)");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(1) + " : " + matcher.group(2));
}
This will match all the attr=val
pair inside the [
and ]
.
OUTPUT: -
attr1 : val1
attr2 : val2
attr3 : val3
UPDATE: -
Since you don't have to do a boundary check in your above string, the above pattern can even be simplified to: -
Pattern pattern = Pattern.compile("(\\w+?)=(\\w+)");
Upvotes: 4