Why is this non-greedy regex grabbing more than I want?
java, non-greedy, regex
Solution
- if you want to make `.*` to be non-greedy you need to add `?` right after `*`.
- `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.
Problem
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.