Question

I would think this should return "state,country" but it's returning "country"

System.out.println("city,state,country".replaceAll("(.*,)?", ""));

Why is it working this way, and how do I make it return "state,country". I want this answer as a regex.

Was it helpful?

Solution

  1. if you want to make .* to be non-greedy you need to add ? right after *.
  2. replaceAll will replace all occurrences of matching parts, so you should probably use replaceFirst

try

System.out.println("city,state,country".replaceFirst(".*?,", ""));

output:

state,country

If you can't use replaceFirst and need to stay with replaceAll then @Reimeus answer is probably what you are looking for.

OTHER TIPS

As the name suggests, replaceAll replaces all matching groups. You need to be more specific where the group is matched. To specify the first matching group you can specify the start of String ^ as an anchor:

"city,state,country".replaceAll("^(.*?,)", "")

You're capturing any group ending in a comma, not just one and that's why it doesn't currently work.

System.out.println("city,state,country".replaceAll("^[^,]*+,", ""));

Try with this expression:

^(.*?,)

or like that:

System.out.println("city,state,country".replaceAll("(.*?,)((?:.*?,)+)", "$2"));

The ? non-greedy flag can only be used after a + or *, in your context, it is a 0-or-1 match.

You want

System.out.println("city,state,country".replaceAll("(.*?,)", ""));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top