1

I want to creating regex to remove some matching string, the string is phone number

Example user input phone number like this:

+jfalkjfkl saj f62 81 7876 asdadad30 asasda36

then output will be like this:

628178763036

at the moment with my current regex ^[\+\sa-zA-Z]+ it can select the part +jfalkjfkl saj f

What is the regex so it also can select the space bewteen number?

e.g:

62(select the space here)81, 81(select the space here)7876

4

5 回答 5

6

我不知道您打算在哪种语言中使用它,但是您可以 [^\d]+用一个空字符串替换这个模式: ,应该可以做到这一点。它会删除所有不是数字的东西。

于 2013-04-28T20:34:04.113 回答
1

使用 PCRE 正则表达式,您应该能够简单地删除任何匹配\D+的 . 例子:

echo "+jfalkjfkl saj f62 81 7876 asdadad30 asasda36" | perl -pe 's/\D+//g'

印刷:

628178763036
于 2013-04-28T21:44:35.383 回答
0

如果您进行替换,您可以使用数字之间的空格重建电话号码:

search:  \D*(\d+)\D*?(\s?)
replace: $1$2
于 2013-04-28T21:25:58.287 回答
0

使用后视和前瞻来断言数字必须在空格之前/之后:

(?<=\d) +(?=\d)

整个正则表达式与空格匹配,因此无需在替换中引用组,只需替换为空白即可。

于 2013-04-28T21:33:02.047 回答
0

看来您需要两个操作:

  1. 删除既不是空白也不是数字的所有内容:

    s/[^ \d]//g;
    
  2. 删除所有多余的空格:

    s/  +/ /g;
    

    如果您还需要删除前导和尾随空格:

    s/^ //;
    s/ $//;
    

    (在用一个空白替换多个空白之后)。

您可以用它\s来表示更多类似空格的字符,而不仅仅是一个空格。

于 2013-04-28T20:56:27.850 回答