r - 使用正则表达式清理电话号码

标签 r regex

我有以下电话号码组成,其中 33 是​​区号:

+331234567
+3301234567
00331234567
003301234567
0331234567
033-123-456-7
0033.1234567

我只期待 331234567

我曾尝试使用 R 清理这些数字

R::tidyverse::str_replace_all(c("+331234567", "033-123-456-7", "0033.1234567"), pattern = "[^0-9.]", replacement = "") removing non-numeric characters
R::tidyverse::str_replace_all("0331234567", pattern = "^0", replacement = "") removing the leading 0
R::tidyverse::str_replace_all("00331234567", pattern = "^00", replacement = "") removing the leading 00

我的问题是如何删除之间的零:3301234567 或 003301234567 或 +3301234567 或 03301234567

感谢任何帮助

最佳答案

你可以使用

gsub("^(?:00?|\\+)330?|\\W", "", x, perl=TRUE)

参见 regex demo .查看R demo online .

如果33之后可以有更多的0在你需要提取的数字之前,将0?替换为0*

详情

  • ^ - 字符串的开始
  • (?:00?|\+) - 000+
  • 330? - 33330
  • | - 或者
  • \W - 任何非单词字符。

关于r - 使用正则表达式清理电话号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65235326/

相关文章:

c# - 两个已知标签之间可能出现不止一次的子字符串的正则表达式

php - 使用正则表达式从地址中提取数字

r - 在 R 中将 NA 设置为 0

R,变异和 "Unsupported type NILSXP for column"

r - Spark 错误 - 小数精度 39 超过最大精度 38

javascript - 如何检查字符串中的数字

c# - 0.0 到 1 的正则表达式

c++ - 这是 C++11 正则表达式错误我还是编译器?

r - 将旧的 r 版本包复制到包含新版本包的新文件夹是否正确?

r - 基准和处理时间结果的差异