Regex 验证jabber id的正则表达式是什么?
现在我使用的是这个regexp:Regex 验证jabber id的正则表达式是什么?,regex,validation,xmpp,Regex,Validation,Xmpp,现在我使用的是这个regexp: ^\A([a-z0-9\.\-_\+]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z$ 我觉得不太好。那么,您所见过的验证JID的最好的正则表达式是什么 为了便于参考,将扩展的Backus Naur形式的JID定义为 jid = [ node "@" ] domain [ "/" resource ] domain = fqdn / address-literal fqdn =
^\A([a-z0-9\.\-_\+]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z$
我觉得不太好。那么,您所见过的验证JID的最好的正则表达式是什么
为了便于参考,将扩展的Backus Naur形式的JID定义为
jid = [ node "@" ] domain [ "/" resource ]
domain = fqdn / address-literal
fqdn = (sub-domain 1*("." sub-domain))
sub-domain = (internationalized domain label)
address-literal = IPv4address / IPv6address
通过快速搜索,请参见:
您的regexp至少在以下几点上是错误的:
- 更容易的测试(您可以独立地对每个部件进行单元测试)
- 更好的性能
- 简单代码
- 可重用性
- 等等
^(?:([^@/<>'\"]+)@)?([^@/<>'\"]+)(?:/([^<>'\"]*))?$
旁白:如果您不熟悉构造(?:),它是一组不向输出中添加组的参数。如果您提供构成合法jabber id的规则,那将很有帮助。ire_和_curses已经修复了我的疏忽,谢谢。我想您还没有意识到您的要求有多高。这个任务非常类似于验证电子邮件地址,这非常非常复杂,不适合正则表达式。检查一下:您的正则表达式的另一个问题是它没有考虑大量在JID中合法但不是a-z0-9的Unicode代码点。
foo (None, 'foo', None)
foo@example.com ('foo', 'example.com', None)
foo@example.com/bar ('foo', 'example.com', 'bar')
example.com/bar (None, 'example.com', 'bar')
example.com/bar@baz (None, 'example.com', 'bar@baz')
example.com/bar/baz (None, 'example.com', 'bar/baz')
bär@exämple.com/bäz ('bär', 'exämple.com', 'bäz')