-2

I have a String

a = "stringWithBraces()"

I want to create the following string

"stringWithBraces(text)"

How do I achieve this using regex?

I tried this :

a.replaceAll("\\(.+?\\)", "text");

But get this :

stringWithBraces()
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
user_mda
  • 18,148
  • 27
  • 82
  • 145

3 Answers3

1

You can use lookaheads and do something like this:

(?<=\().*?(?=\))

Live Demo

Thus doing this:

String a = "stringWithBraces()";
a = a.replaceAll("(?<=\\().*?(?=\\))", Matcher.quoteReplacement("text"));

System.out.println(a);

Outputs:

stringWithBraces(text)

Note that in relation to replaceAll() then the replacement string has some special character. So you should most likely use Matcher.quoteReplacement() in order to escape those and be safe.

vallentin
  • 23,478
  • 6
  • 59
  • 81
0

You can use this :

a = a.replaceAll("\\((.*?)\\)", "(text)");

You have to replace every thing between parenthesis with (text)

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
0

+ requires at least one char, the ? added here means the shortest match, so "...(.)...(.)..." would not continue to find ".)...(.".

a.replaceAll("\\(.*?\\)", "(text)");

You might have intended replaceFirst; though I think not.

You might also let the dot . match new line chars, for mult-line matches, using the DOT_ALL option (?s):

a.replaceAll("(?s)\\(.*?\\)", "(text)");
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138