ammu
ammu

Reputation: 864

replace specific braces text using regular expression in java

I need to found the text inside braces () and replace them with some text , the regular expression' I have written won't work, please suggest.

String x = "([(34mm)(89)[]";

I need the output as ([(1)(1)[]

System.out.println(x.replaceAll("\\(.*\\)", "1")); // not giving desired o/p

In addition I also want the replaced text value like I need 34mm and 89 so that I can do some computation on it, let me know that too.

Thanks.

Upvotes: 0

Views: 75

Answers (2)

nhahtdh
nhahtdh

Reputation: 56809

Without look-ahead or look-behind:

System.out.println(x.replaceAll("\\([^()]*\\)", "(1)"));

If you can assume that there will be no nested or stray ( or ) inside a pair of parentheses, the problem is simplified to disallowing () inside the pair of parentheses [^()]*, instead of allowing it like in your original code.

If you want to match properly balanced parentheses, then it is not possible in Java regex (either that, or it will require some kind of convoluted trick). In such cases, just fall back to looping solution.

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

Use a positive lookahead and lookbehind like below,

String x = "([(34mm)(89)[]";
System.out.println(x.replaceAll("(?<=\\()[^()]*(?=\\))", "1"));

Output:

([(1)(1)[]

Explanation:

  • (?<=\\() Strings we are going to match must be preceded by an ( symbol.
  • [^()]* Match any character but not of ( or ) zero or more times.
  • (?=\\)) Match must be followed by an ) symbol.

Upvotes: 2

Related Questions