AutoMater AutoMater - 5 months ago 9
Java Question

How to create a regEx to extract value from a string with square brackets in Java

I have a string "Something[Anything]".
First I want to check whether string contains Square brackets if yes then I want this string to be separated in "Something" & "[Anything]".
Need some help with regEx for this.
Thanks in Advance.

Answer

Try this:

    String test = "Something[Anything]";
    if (test.matches(".*\\[.*\\].*")) { // checks if in the string presents open and close square brackets
        Pattern pat = Pattern.compile("(.*?)(\\[.*?\\])");
        Matcher matcher = pat.matcher(test);
        matcher.find();
        System.out.println(matcher.group(1));
        System.out.println(matcher.group(2));
    }

Outputs:

Something
[Anything]

Or, as suggested by @madatx, without first check:

    Pattern pat = Pattern.compile("(.*?)(\\[.*?\\])");
    Matcher matcher = pat.matcher(test);
    if (matcher.find()) {
        System.out.println(matcher.group(1));
        System.out.println(matcher.group(2));
    }

Same output.

Comments