Reputation: 43
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?
Upvotes: 4
Views: 135
Reputation: 133458
With your shown samples and attempts please try following regex:
^.*?\(([^*]*)\*\S+\)$
Here is the Regex Online Demo and here is the Java code Demo for used regex.
Explanation: Adding detailed explanation for used Regex.
^ ##Matching starting of the value here.
.*?\( ##Using lazy match here to match till ( here.
( ##Creating one and only capturing group of this regex here.
[^*]* ##Matching everything till * here.
) ##Closing capturing group here.
\* ##Matching * here.
\S+ ##Matching non-spaces 1 or more occurrences here.
\)$ ##Matching literal ) here at the end of the value.
Upvotes: 2
Reputation: 163217
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 lineString string = "1.2.3 (1.234*xY)";
System.out.println(string.replaceFirst("^[^(]*\\(([^*]+)\\*.*", "$1"));
Output
1.234
Upvotes: 3
Reputation: 784998
You may use this regex to match:
[^(]*\(|\*.*
and replace with an empty string.
RegEx Demo:
[^(]*\(
: Match 0 or more characters that are not (
followed by a (
|
: OR\*.*
: Match *
and everything after thatJava Code:
String s = "1.2.3 (1.234*xY)";
String r = s.replaceAll("[^(]*\\(|\\*.*", "");
//=> "1.234"
Upvotes: 3