Simply try using String#split()
method.
String str = "[foo-bar] [baz][qux]";
String[] array = str.substring(1, str.length() - 1).split("\\]\\s*\\[");
Question
Need help with parsing line where keywords included in brackets []
.
I tried but have wrong result:
public class App {
public static void main(String[] args) {
Matcher mtr = Pattern.compile("(\\w+-\\w+|\\w+)+").matcher("[foo-bar] [baz][qux]");
if (mtr.find()) for (int i = 0; i < mtr.groupCount(); i++) {
System.out.println(mtr.group(i));
}
}
}
foo-bar
foo-bar
baz
qux
What should be regex that parse string as on last example ?
Solution
Simply try using String#split()
method.
String str = "[foo-bar] [baz][qux]";
String[] array = str.substring(1, str.length() - 1).split("\\]\\s*\\[");
OTHER TIPS
try this
Matcher mtr = Pattern.compile("[\\w-]+").matcher("[foo-bar] [baz][qux]");
while(mtr.find()) {
System.out.println(mtr.group());
}
Instead of if (mtr.find())
:
while (mtr.find())
for (int i = 0; i < mtr.groupCount(); i++) {
System.out.println(mtr.group(i));
}
i.e. you need to call matcher#find()
inside a loop to have global matched returned.
try this retular expression
\[[^\[\]]*\]
http://rubular.com/r/heMGeTMjuB
alternatively, this one is similar, and will parse things such as "[foo[bar]"
as foo[bar
\[(.*?)\]
As long as your brackets can't be nested, you can try the regex
\[([^\]]*)\]
and extract the first capturing group.
That is:
Matcher mtr = Pattern.compile("\\[([^\\]]*)\\]").matcher("[foo-bar] [baz][qux]");
while (mtr.find())
System.out.println(mtr.group(1));
foo-bar baz qux