2010-12-15 61 views
2

我有一个正则表达式看起来像这样:正则表达式崩溃的iPhone

^(\+\d\d)?(?(?<=\+\d\d)((|)\(0\)(|)| |)|(0))(8|\d\d\d?)[-/ ]?\d\d(?\d){1,4} ?\d\d$ 

它用来验证瑞典的电话号码。在其他环境中,比如.NET,这个正则表达式工作正常,但是在Objective-c中,它会导致崩溃,并说正则表达式不是有效的正则表达式。在正则表达式方面,我远非专家,所以我想知道是否有人可以帮我找到这个正则表达式不起作用的原因。

我使用Reggy验证正则表达式和问题似乎是这组

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

,但我想不出为什么......如果我删除从开始和结束(?)这一组中,撞车消失。有谁知道(?是做什么的?据我所知,?用于指定一个组是可选的,但是它在组的最开始使用时意味着什么?

回答

1

我做你的正则表达式“清晰”通过将其转化为详细的形式和注释,所以你可以看到它正在试图做的事。我希望你会同意,大部分是赚不了多少意义:

^     # 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$ 
+0

谢谢!我还没有自己创建正则表达式,所以我不确定规则和允许的电话号码格式。它来自我的客户正在使用的另一个(网络)应用程序,他们现在希望在iPhone应用程序中实施相同的验证。 – andlin 2010-12-15 12:11:51

+0

这就是我所期望的。将编辑我的答案。虽然你一定要告诉你的客户,你正在用一些破碎的东西来取代某些东西。 – 2010-12-15 15:54:14

相关问题