Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

Input:
1.2.3 (1.234*xY)

Needed Output:
1.234

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"));

Output

1.234
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading