jmb95
jmb95

Reputation: 97

Regex optional group with | at the beginning not working

I can have two kind of imput strings:

  1. text1
  2. 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

Answers (2)

BackSlash
BackSlash

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.

DEMO

Upvotes: 1

Madbreaks
Madbreaks

Reputation: 19539

How about "A|B".replace('|', '-'); -- there's no reason to use a RegEx here.

Upvotes: 1

Related Questions