未知转义序列 - 正则表达式

发布于 2024-11-26 12:47:55 字数 451 浏览 2 评论 0原文

我想验证我使用 RegexKitLite.h 的电子邮件文本。我正在做如下事情:

NSString *strEmail = [txtEmail text];
                NSRange range = [strEmail rangeOfRegex:@"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"];
                NSLog(@"%@",range);  

现在我只是检查这是否有效。但我在第二行遇到错误。日志什么也没说。但第二行有一个警告:

Unknown escape sequence '\.'  

可能是什么问题?是表述有问题还是有其他问题?

I want to validate email text for which I am using RegexKitLite.h. I am doing things as follows :

NSString *strEmail = [txtEmail text];
                NSRange range = [strEmail rangeOfRegex:@"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"];
                NSLog(@"%@",range);  

For now I am just checking if this works. But I am getting error in second line. Log doesn't say anything. But there is a warning in second line which says :

Unknown escape sequence '\.'  

What might be the problem? Is there something wrong in expression or is there some other issue?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

离不开的别离 2024-12-03 12:47:55

您不需要转义字符类中的点。大多数正则表达式引擎都会忽略这种错误,Objective C 的似乎更严格。试试这个:

rangeOfRegex:@"^[a-zA-Z][\w.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z.]*[a-zA-Z]$"

但是(与问题无关),这是一个相当奇怪的电子邮件验证正则表达式,因为它会拒绝许多有效的电子邮件地址并允许许多无效的电子邮件地址。我不知道您的目标是什么,但通常最好不要对验证正则表达式过于严格,而是通过实际向该地址发送电子邮件并查看它是否失败来进行验证。

You don't need to escape the dot in a character class. Most regex engines ignore this kind of error, Objective C's seems to be more strict. Try this:

rangeOfRegex:@"^[a-zA-Z][\w.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z.]*[a-zA-Z]$"

However (and unrelated to the problem), that's a fairly strange e-mail validation regex as it will reject many valid e-mail addresses and allow many invalid ones. I don't know what you're aiming for here, but it is generally a good idea not to be too strict with validating regexes and rather do the validation by actually sending an e-mail to that address and see if it fails.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文