如何将以下模式与正则表达式匹配?

时间:2014-06-16 10:28:26

标签: regex

我有一个常规的exp,如下(((\(?\+?1?\)?)\s?-?)?((\(?\d{3}\)?\s?-?\s?))?\s?\d{3}\s?-?\s?\d{4}){1}它匹配这种格式的数字xxx-xxx-xxxx;其中x是0-9的数字。如何使其与点数(。)匹配,例如xxx.xxx.xxxx,并与xxx.xxx.xxx匹配

2 个答案:

答案 0 :(得分:3)

更简单的正则表达式

我建议将正则表达式简化为此(请参阅demo匹配且不匹配的内容):

^\d{3}([-.])\d{3}\1\d{3,4}$

此表达式的一个好处是我们确保在数字组之间使用相同的分隔符-.。我们通过使用([-.])将分隔符捕获到组1,然后使用\1稍后引用该捕获来执行此操作。

<强>解释

^             # assert position at the beginning of the string
\d{3}         # match any digit from 0-9 (3 times)
(             # group and capture to \1
  [-.]        # match any character in the list: '-', '.'
)             # end of first capturing group
\d{3}         # any digit from 0-9 (3 times)
\1            # what was matched by group 1
\d{3,4}       # match any digit (0-9) (3 or 4 times)
$             # assert position at the end of the string (before an optional \n)

答案 1 :(得分:1)

稍作修改即:

(((\(?\+?1?\)?)\s?[-.]?)?((\(?\d{3}\)?\s?[-.]?\s?))?\s?\d{3}\s?[-.]?\s?\d{3,4}){1}

Regular expression visualization

原文:

Regular expression visualization

相关问题