Reputation: 97
I can have two kind of imput strings:
text1
text1|text2
I want to print the output string: text1-text2
I have tried this:
System.out.println("A|B".replaceAll("(.+)\\|(.+)?", "$1-$2")); // I expect A-B
System.out.println("A|" .replaceAll("(.+)\\|(.+)?", "$1-$2")); // I expect A-
System.out.println("A" .replaceAll("(.+)(\\|(.+))?", "$1-$3")); // I expect A-
System.out.println("A|B".replaceAll("(.+)(\\|(.+))?", "$1-$3")); // I expect A-B
With the following output:
A-B
A-
A-
A|B-
What I'm doing wrong in the last sentece ?
Upvotes: 1
Views: 43
Reputation: 22233
.+
captures everything but newlines. Since the second group is optional, it will capture A|B
.
So $1
will be A|B
, while $2
and $3
will be empty.
You need to use
(.+?)(\\|(.+))?
In order to make it work. The ?
means As few times as possible.
Upvotes: 1
Reputation: 19539
How about "A|B".replace('|', '-');
-- there's no reason to use a RegEx here.
Upvotes: 1