Replace all characters before and after specific characters


I need to replace all characters in a string which come before an open parenthesis but come after an asterisk:

1.2.3 (1.234*xY)

Needed Output:

I tried the following:

(string.replaceAll(".*\\(|\\*.*", "");

but I ran into an issue here where "Matcher.matches() is false" even though there are two matches… What is the most elegant way to solve this?

>Solution :

You could try matching the whole string, and replace with capture group 1


The pattern matches:

  • ^ start of string
  • [^(]*\( Match any char except ( and then match (
  • ([^*]+) Capture in group 1 matching any char except *
  • \*.* Match an asterix and the rest of the line

Regex demo | Java demo

String string = "1.2.3 (1.234*xY)";
System.out.println(string.replaceFirst("^[^(]*\\(([^*]+)\\*.*", "$1"));



Leave a Reply Cancel reply