正则表达式替换所有非数字但允许 '+' 前缀

标签 regex kotlin

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

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

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

最佳答案

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

(?<=.)\+|[^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 +

关于正则表达式替换所有非数字但允许 '+' 前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66470310/

相关文章:

Kotlin 对象,实现与实例

android - 如何在单一 Activity 架构中使用 BottomNavigationView

android - 基类中的 ViewModelProviders.get(...)

android - Kotlin DataBinding 将静态函数传递到布局 xml

mysql - SQL : get substring from one column and inserting it into other column

r - 如何提取R中的第一个字符串

javascript - 从 URL 中删除重复的正斜杠

regex - 匹配空格但不匹配换行符

javascript - 通过 JavaScript 中的 RegEx 逐步验证电子邮件地址

android - 为什么 Android 需要 View 模型工厂?