Regex to replace all non numbers but allow a '+' prefix

Viewed 326

I want to delete all invalid letters from a string which should represent a phone number. Only a '+' prefix and numbers are allowed. I tried in Kotlin with

"+1234abc567+".replace("[^+0-9]".toRegex(), "")

It works nearly perfect, but it does not replace the last '+'. How can I modify the regex to only allow the first '+'?

2 Answers

You could do a regex replacement on the following pattern:

(?<=.)\+|[^0-9+]+

Sample script:

String input = "+1234abc567+";
String output = input.replaceAll("(?<=.)\\+|[^0-9+]+", "");
System.out.println(input);   // +1234abc567+
System.out.println(output);  // +1234567

Here is an explanation of the regex pattern:

(?<=.)\+  match a literal + which is NOT first (i.e. preceded by >= 1 character)
|         OR
[^0-9+]+  match one or more non digit characters, excluding +

You can use

^(\+)|\D+

Replace with the backreference to the first group, $1. See the regex demo.

Details:

  • ^(\+) - a + at the start of string captured into Group 1
  • | - or
  • \D+ - one or more non-digit chars.

NOTE: a raw string literal delimited with """ allows the use of a single backslash to form regex escapes, such as \D, \d, etc. Using this type of string literals greatly simplifies regex definitions inside code.

See the Kotlin demo:

val s = "+1234abc567+"
val regex = """^(\+)|\D+""".toRegex()
println(s.replace(regex, "$1"))
// => +1234567
Related