如何去除字符串中除第一个字符以外的所有非数字? [英] How can I strip all non digits in a string except the first character?

查看:47
本文介绍了如何去除字符串中除第一个字符以外的所有非数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,我想确保其格式始终为 + 后跟数字.
以下将起作用:

I have a string that I want to make sure that the format is always a + followed by digits.
The following would work:

String parsed = inputString.replaceAll("[^0-9]+", "");  
if(inputString.charAt(0) == '+') {  
   result = "+" + parsed;  
}  
else {
  result = parsed;  
}  

但是有一种方法可以在 replaceAll 中使用一个正则表达式,该正则表达式会将 + (如果存在)保留在字符串的开头,并替换其中的所有非数字第一行?

But is there a way to have a regex in the replaceAll that would keep the + (if exists) in the beginning of the string and replace all non digits in the first line?

推荐答案

使用给定正则表达式的以下语句将完成此工作:

The following statement with the given regex would do the job:

String result = inputString.replaceAll("(^\\+)|[^0-9]", "$1");


(^\\+)    find either a plus sign at the beginning of string and put it to a group ($1),
|         or
[^0-9]    find a character which is not a number
$1        and replace it with nothing or the plus sign at the start of group ($1)

这篇关于如何去除字符串中除第一个字符以外的所有非数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆