user3157090
user3157090

Reputation: 537

How to get the values from outside the braces using regex

Please see the requirement below.

String s1 = "||||(;)||(;;)||(;)";

output from the above string should be: ||||||

String s2 = ";;(||)";

output from the above string should be: ;;

String s3 = ";;";

output from the above string should be: ;;

I was trying below example, but the output is for the s1 is ;

Pattern p = Pattern.compile("\\(^(.*?)\\)");
Matcher m = p.matcher(filter);

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

Upvotes: 0

Views: 78

Answers (2)

Kevin Sandow
Kevin Sandow

Reputation: 4033

Since you're only removing everything inside braces you can use:

str.replaceAll("\([^\)]*\)", "");

Upvotes: 2

TheLostMind
TheLostMind

Reputation: 36304

Try this regex ..

public static void main(String[] args) {
    String s1 = "||||(;)||(;;)||(;)";
    Pattern p = Pattern.compile("(.*?)(?:\\(.*?\\))");
    Matcher m = p.matcher(s1);
    while (m.find()) {
        System.out.println(m.group(1));
    }

}

O/P :

case -1 : s1 = "||||(;)||(;;)||(;)";
||||
||
||

case -2 :   s1 = ";;(||)";

    ;;

Upvotes: 0

Related Questions