删除字符串中逗号之前的字符

use*_*174 12 java string

我想知道在字符串中逗号之前删除字符的最佳方法是什么,以及删除逗号本身,只留下字符串中逗号之后的字符,如果字符串表示为'city,country ".

提前致谢

Dan*_*lan 32

所以你要

城市,国家

成为

国家

一个简单的方法是:

public static void main(String[] args) {
    System.out.println("city,country".replaceAll(".*,", ""));
}
Run Code Online (Sandbox Code Playgroud)

这虽然"贪婪",但意味着它会改变

市,州,国家

成

国家

在您的情况下,您可能希望它成为

州,国家

我无法从你的问题中说出来.

如果您想要"非贪婪"匹配,请使用

System.out.println("city,state,country".replaceAll(".*?,", ""));
Run Code Online (Sandbox Code Playgroud)

这将输出

国家,国家

  • 如果他不希望>城市,州,国家成为>州,国家将`replaceAll`改为`replaceFirst``System.out.println("city,state,country".replaceFirst(".*,", ""));"但是,问题不清楚 (2认同)