Advertisements
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
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
String string = "1.2.3 (1.234*xY)";
System.out.println(string.replaceFirst("^[^(]*\\(([^*]+)\\*.*", "$1"));
Output
1.234