0

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));
        }
    }
}

Result(wrong):

foo-bar

Me need:

foo-bar
baz
qux

What should be regex that parse string as on last example ?

1
  • 1
    you need to call find() in a loop until it stops finding. the groups are the groups for a single match, not all the matches. Commented May 13, 2014 at 18:40

5 Answers 5

1

Simply try using String#split() method.

String str = "[foo-bar] [baz][qux]";
String[] array = str.substring(1, str.length() - 1).split("\\]\\s*\\[");
Sign up to request clarification or add additional context in comments.

2 Comments

This will leave "[" and "]" in array[0] and array[array.length - 1] which is not wanted. "[foo-bar" instead of foo-bar.
I don't think so. That's why substring is used.
1

try this

    Matcher mtr = Pattern.compile("[\\w-]+").matcher("[foo-bar] [baz][qux]");
    while(mtr.find()) {
        System.out.println(mtr.group());
    }

Comments

1

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.

Comments

1

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

\[(.*?)\]

http://rubular.com/r/IzPI0RcLmS

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.