How can I strip all non digits in a string except the first character?

后端 未结 5 1836
我在风中等你
我在风中等你 2021-01-19 14:34

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 = input         


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-19 15:02

    You can use this expression:

    String r = s.replaceAll("((?

    The idea is to replace any non-digit when it is not the initial character of the string (that's the (? 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.

提交回复
热议问题