用于从电话号码中提取业务分机号的正则表达式
我正在尝试编写一个正则表达式来从完整的电话号码字符串中提取电话分机号。这应该适用于这样的数字:777.777.7777 x 7302
它也应该适用于使用“ext”、“EXT”、“Ext”、“eXt”、“ext.”和“Ext”。本质上只是涵盖了它的所有常见用途。
我只需要“x 7302”部分。事实上,一旦我提取它,我将把它只剩下分机号。
有人可以帮我吗?当正则表达式变得更加复杂时,我会遇到一些困难。
我正在 PHP 函数(preg_match)中执行此操作,如果这对任何人都有帮助的话。
I am having the dang-est time trying to write a regex that will extract the phone extension from a full phone number string. This should work on a number like this one: 777.777.7777 x 7302
It should also work using "ext", "EXT", "Ext", "eXt", "ext.", and "Ext ". Essentially just cover all the common ground use of it.
I just need the "x 7302" part. In fact I am just going to strip it down to just the extension number once I extract it.
Can anyone help me please? Regular expressions are something that I struggle with when they get more complex.
I am doing this in a PHP function (preg_match) if that will help anyone.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这可能有助于为您提供一些帮助:
使用
i
修饰符(在末尾)使正则表达式不区分大小写,以便匹配ext
的所有组合。我使用一个组来提供这两种变体:ext
或x
:(ext|x)
。剩下的就是寻找末尾的数字,EXT 和数字之间可以有空格。
This probably helps to give you something to play with:
Use the
i
modifier (at the end) to make the regex case insensitive so to match all combinations ofext
. I used a group to offer both variant:ext
orx
:(ext|x)
.The rest is looking for a number at the end, and a space is possible between EXT and the number.
尝试使用正则表达式:
输出:
try with regex:
Output:
这是一个更简单的正则表达式,假设输入与您提供的内容类似。
It is an simpler regex assuming that the input is similar to what you have provided.
这应该为您做
第一组匹配由破折号或点分隔的数字。第二组与您的分机字符串匹配,第三组与您的分机号码匹配。
This should do it for you
The first set matches the numbers separated by dash or dot. The second set matches your extension string and the third set matches your extension number.
如果您只需要字符串的最后一个数字,则可以使用:
\D+
至少一位非数字,后跟:(\d+)
至少一位数字(捕获使用括号)$
在字符串末尾。If you just want the last numbers of the string, you can use:
\D+
at least one non-digit followed by:(\d+)
at least one digit (captured using parenthesis)$
at the end of the string.我对正则表达式有点怀疑,所以当我说是否可以使用 PHP 函数“explode()”分割字符串并使用“x”字符作为分隔符时,我有点偏见?
如果您不熟悉该函数,这里是该函数的 PHP 手册的链接:
Explode( )
I am a bit leery of regular expression, so I'm a bit biased when I say, is it possible to just split the string using the PHP function "explode()", using the 'x' character as your delimiter?
Here is a link to the PHP manual for that function if you are not familiar with it:
Explode()
试试这个功能:
Try this function: