首页 > 解决方案 > 正则表达式替换所有非数字,但允许使用“+”前缀

问题描述

我想从应该代表电话号码的字符串中删除所有无效字母。只允许使用“+”前缀和数字。我在 Kotlin 中尝试过

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

它工作得近乎完美,但它不能取代最后一个“+”。如何修改正则表达式以仅允许第一个“+”?

标签: regexkotlin

解决方案


您可以对以下模式进行正则表达式替换:

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

示例脚本:

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

以下是正则表达式模式的解释:

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

推荐阅读