我认为这应该返回“州,国家”,但它正在返回“国家”
System.out.println("city,state,country".replaceAll("(.*,)?", ""));
为什么它以这种方式工作,以及如何使其返回“州,国家”。我想要这个答案作为正则表达式。
我认为这应该返回“州,国家”,但它正在返回“国家”
System.out.println("city,state,country".replaceAll("(.*,)?", ""));
为什么它以这种方式工作,以及如何使其返回“州,国家”。我想要这个答案作为正则表达式。
.*变得不贪婪,你需要?在*.replaceAll将替换所有匹配的部分,所以你应该使用replaceFirst 尝试
System.out.println("city,state,country".replaceFirst(".*?,", ""));
输出:
state,country
如果您不能使用replaceFirst并且需要留下来,replaceAll那么@Reimeus 的答案可能就是您想要的。
顾名思义,replaceAll替换所有匹配的组。您需要更具体地匹配组的位置。要指定第一个匹配组,您可以将起点指定String ^为锚点:
"city,state,country".replaceAll("^(.*?,)", "")
您正在捕获任何以逗号结尾的组,而不仅仅是一个,这就是它目前不起作用的原因。
System.out.println("city,state,country".replaceAll("^[^,]*+,", ""));
试试这个表达式:
^(.*?,)
或者像这样:
System.out.println("city,state,country".replaceAll("(.*?,)((?:.*?,)+)", "$2"));
这 ?非贪婪标志只能在 + 或 * 之后使用,在您的上下文中,它是 0 或 1 匹配。
你要
System.out.println("city,state,country".replaceAll("(.*?,)", ""));