regex - 正则表达式替换所有非数字,但允许使用“+”前缀
问题描述
我想从应该代表电话号码的字符串中删除所有无效字母。只允许使用“+”前缀和数字。我在 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 +
推荐阅读
- r - Shiny App中的不同行数错误
- angular - 我如何以角度获取 status_code 400
- amazon-web-services - 如何在 DynamoDB 中使用 GSI 将投影属性附加到查询结果中?
- php - 如何使用 PHP 检查字符串是否是有效的 XHTML?
- reactjs - 用 Jest 模拟 window.get()
- haskell - 返回数据树 Haskell 中的分支
- node.js - 有没有办法将 macOS 父子功能添加到 windows 和 linux 的电子子窗口中?
- azure - 将机器人连接到 Azure 机器人服务团队频道
- php - 使用 Require 然后在类中使用
- scala - 为 Scala 项目生成可执行 Jar