我想从应该代表电话号码的字符串中删除所有无效字母。只允许使用“+”前缀和数字。 我在 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/