如何在正则表达式中使用 if-then ?
我正在为 Postfix 编写一个正则表达式来定义其虚拟域映射。我想捕获一个域中除两个之外的所有子域。
假设我的域名是 example.com 并且两个排除子域是 in,mail,我编写了以下正则表达式:
(?(?!mail|in) .+\.example.com)
它应该识别 whatever.example.com,但不能识别 in.example.com 或 mail.example。 com。
它确实可以在 RegExr 中工作,但在 Postfix 和 Ruby 中不起作用。我假设我使用了 if-then 错误,正确的语法是什么?还有其他选择吗?
I'm writing a regular expression for Postfix that defines its virtual domains map. I want to catch all subdomains of a domain except for two.
Assuming my domain is example.com and the two exclusion subdomains are in,mail, I wrote the following regular expression:
(?(?!mail|in).+\.example.com)
It supposed to recognize whatever.example.com but not in.example.com or mail.example.com.
It does work in RegExr, but it doesn't work in Postfix nor Ruby. I'm assuming that I'm using if-then wrong, what is the correct syntax? Are there other options?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用锚点,那么它应该可以工作。
请参阅 Rubular 上的此处
开头的锚点
\b
是词边界。这可以确保您的子域之前有非单词字符,因此它不再与mail
中的ail
匹配。这匹配
而不是
更新
可能
^
锚点是这里更好的选择。这将匹配字符串的开头。对于您的示例来说,这没有什么区别,但如果您的 URL 以非单词字符开头,那么单词边界就会出错。
If you use an anchor, then it should work.
See it here on Rubular
The anchor at the beginning
\b
is a word boundary. This assures that there is non word character before your subdomain and therefor it does not matchail
frommail
anymore.This matches
and not
UPDATE
Probably the
^
anchor is the better choice here. This would match the start of the string.For your examples it makes no difference, but if your URL starts with a non-word character then it would be wrong with the word boundary.