How to get strings in parentheses into array with

2019-05-31 04:56发布

问题:

Lets say I have string like this:

String q = "foo (one) bla (two) zoo key hola (tree) (four) five"

I want to extract the strings in parentheses into string array

so this would be true:
stringArray[3].equals("four") 

Is there something in commons package or other trick to do this?

回答1:

    Pattern p = Pattern.compile("\\((.*?)\\)");

    Matcher m = p.matcher("abc (one) abc (two) abc");

    List<String> result = new ArrayList<String>();

    while(m.find())
        result.add(m.group(1));