我做你的正则表达式“清晰”通过将其转化为详细的形式和注释,所以你可以看到它正在试图做的事。我希望你会同意,大部分是赚不了多少意义:
^ # Start of string
(\+\d\d)? # Match + and two digits optionally, capture in backref 1
(?(?<=\+\d\d) # Conditional: If it was possible to match +nn previously,
(\s?\(0\)\s?|\s|) # then try to match (0), optionally surrounded by spaces
# or just a space, or nothing; capture that in backref 2
| # If it was not possible to match +nn,
(0) # then match 0 (capture in backref 3)
) # End of conditional
(8|\d\d\d?) # Match 8 or any two-three digit combination --> backref 4
[-/\s]? # match a -,/or space optionally
\d\d # Match 2 digits, don't capture them
(\s?\d){1,4} # Match 1 digit, optionally preceded by spaces;
# do this 1 to 4 times, and capture only the last match --> backref 5
\s?\d\d # Match an optional space and two digits, don't capture them
$ # End of string
在其目前的形式,它验证串像
+46 (0) 1234567
+49 (0) 1234567
+00 1234567
+99 08 11 1 11
012-34 5 6 7 8 90
,并在字符串失败像
+7 123 1234567
+346 (77) 123 4567
+46 (0) 12/34 56 7
所以我非常怀疑它正在做它应该做的。除此之外,大多数正则表达式可以被简化很多,放弃了正在使用正则表达式库的条件。如果您的客户坚持要求优化某些内容没有多大意义,但是如果您的客户坚持,这里是一个功能完全相同但没有条件的版本:
^(?:\+\d\d(?: ?(?:\(0\)\s?)?)?|0)(?:8|\d\d\d?)[-/ ]?\d\d(?: ?\d){1,4} ?\d\d$
谢谢!我还没有自己创建正则表达式,所以我不确定规则和允许的电话号码格式。它来自我的客户正在使用的另一个(网络)应用程序,他们现在希望在iPhone应用程序中实施相同的验证。 – andlin 2010-12-15 12:11:51
这就是我所期望的。将编辑我的答案。虽然你一定要告诉你的客户,你正在用一些破碎的东西来取代某些东西。 – 2010-12-15 15:54:14