开发者

How to write regular matching expression. -Java

开发者_如何学JAVAI want to write matching expression to read string between parentheses () from a big string. eg: the big string is:-

(something), (something2), (something3)

How can I write matching expression for this to read something, something2, something3 in groups.


You can't read all those groups in one go but using Matcher#find() and this expression you might read those: \(([^\(\)]*)\) (reads: match must start with (, must contain any number of characters not being ( or ) - those form your group - , and must end with ) ).

Note that the escape in the brackets is not necessary, but done for consistency, since they are needed outside.

Pattern p = Pattern.compile("\\(([^\\(\\)]*)\\)");
Matcher m = p.matcher( "(something), (something2), (something3)" );

while(m.find())
{
  System.out.println(m.group( 1 ));
}

This prints:

something
something2
something3


You can read all the somethings into an array with one line:

String[] somethings = input.replaceAll("(^.?*\\(|\\)[^\\(]*$)", "").split("\\).*?\\(");

Here's some test code:

public static void main(String... args) throws InterruptedException {
    String input = "foo (something1) (something2), blah (something3) bar";
    String[] somethings = input.replaceAll("(^[^\\(]*\\(|\\)[^\\(]*$)", "").split("\\).*?\\(");
    System.out.println(Arrays.toString(somethings));
}

Output:

[something1, something2, something3]


Following program will get required output

public class RegexTestStrings {

    public static final String EXAMPLE_TEST = "(something),(something2),(something3)";

    public static void main(String[] args) {
        String[] splitString = (EXAMPLE_TEST.split("\\("));
        System.out.println(splitString.length);
        for (String string : splitString) {
            System.out.println(string.replace(")",""));
        }
    }
}

First, it split all starting with ( and after that replace ) to "" so you will get output as:

something,

something2,

something3
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜