How can I strip all non digits in a string except

2020-04-16 04:52发布

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;  
}  

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?

5条回答
男人必须洒脱
2楼-- · 2020-04-16 05:31

What about just

(?!^)\D+

Java string:

"(?!^)\\D+"

Demo at regex101.com

  • \D matches a character that is not a digit [^0-9]

  • (?!^) using a negative lookahead to check, if it is not the initial character

查看更多
Melony?
3楼-- · 2020-04-16 05:38

try this

1- This will allow negative and positive number and will match app special char except - and + at first position.

(?!^[-+])[^0-9.]

2- If you only want to allow + at first position

(?!^[+])[^0-9.]
查看更多
对你真心纯属浪费
4楼-- · 2020-04-16 05:47

You can use this expression:

String r = s.replaceAll("((?<!^)[^0-9]|^[^0-9+])", "");

The idea is to replace any non-digit when it is not the initial character of the string (that's the (?<!^)[^0-9] part with a lookbehind) or any character that is not a digit or plus that is the initial character of the string (the ^[^0-9+] part).

Demo.

查看更多
▲ chillily
5楼-- · 2020-04-16 05:50

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)
查看更多
一夜七次
6楼-- · 2020-04-16 05:52

Yes you can use this kind of replacement:

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

if present and before the first digit in the string, the + character is captured in group 1. For example: dfd+sdfd12+sdf12 returns +1212 (the second + is removed since its position is after the first digit).

查看更多
登录 后发表回答