[英]How to remove commas at the end of any string
我有字符串"a,b,c,d,,,,, "
, ",,,,a,,,,"
我希望这些字符串分别转换为"a,b,c,d"
和",,,,a"
。
我正在为此写一个正则表达式。 我的java代码看起来像这样
public class TestRegx{
public static void main(String[] arg){
String text = ",,,a,,,";
System.out.println("Before " +text);
text = text.replaceAll("[^a-zA-Z0-9]","");
System.out.println("After " +text);
}}
但这是删除所有逗号。
如何写这个来实现上面给出的?
采用 :
text.replaceAll(",*$", "")
正如@Jonny在评论中所提到的,也可以使用: -
text.replaceAll(",+$", "")
你的第一个例子最后有一个空格,所以它需要匹配[, ]
。 当多次使用相同的正则表达式时,最好先预先编译它,它只需要替换一次,并且只有至少删除一个字符( +
)。
简单版本:
text = text.replaceFirst("[, ]+$", "");
测试两个输入的完整代码:
String[] texts = { "a,b,c,d,,,,, ", ",,,,a,,,," };
Pattern p = Pattern.compile("[, ]+$");
for (String text : texts) {
String text2 = p.matcher(text).replaceFirst("");
System.out.println("Before \"" + text + "\"");
System.out.println("After \"" + text2 + "\"");
}
产量
Before "a,b,c,d,,,,, "
After "a,b,c,d"
Before ",,,,a,,,,"
After ",,,,a"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.