Java – why is this non greedy regular expression more than I want?

I think it should return to "state, country", but it is returning to "country"

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

Why does it work this way and how to get it back to the "state, country" I hope the answer is a regular expression

Solution

As the name suggests, replaceall replaces all matching groups You need to match the location of the group more specifically To specify the first matching group, you can specify the beginning of the string as the anchor:

"city,country".replaceAll("^(.*?,)","")
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>