前瞻断言

发布于 2024-11-29 09:05:02 字数 462 浏览 5 评论 0原文

我正在尝试使用 Python 中的正则表达式来匹配有效域名中的标签:

DOMAIN_LABEL_RE = """
\A(
(?<![\d\-]) # cannot start with digit or hyphen, looking behind
([a-zA-Z\d\-]*?)
([a-zA-Z]+)# need at least 1 letter
([a-zA-Z\d\-]*?)
(?!\-) # cannot end with a hyphen, looking ahead
)\Z
"""

我正在尝试使用肯定和否定断言来避免标签开头或结尾处出现连字符。

但字符串“-asdf”仍然匹配: e.match(DOMAIN_LABEL_RE, "-asdf", re.VERBOSE).group()

我不明白为什么它仍然匹配。

感谢您的任何帮助。

M。

I'm trying to match a label within a valid domain name using a regular expression in Python:

DOMAIN_LABEL_RE = """
\A(
(?<![\d\-]) # cannot start with digit or hyphen, looking behind
([a-zA-Z\d\-]*?)
([a-zA-Z]+)# need at least 1 letter
([a-zA-Z\d\-]*?)
(?!\-) # cannot end with a hyphen, looking ahead
)\Z
"""

I'm trying to use a positive and negative assertion to avoid a hyphen at the beginning or end of the label.

But the string "-asdf" still matches:
e.match(DOMAIN_LABEL_RE, "-asdf", re.VERBOSE).group()

I don't understand why it's still matching.

Thanks for any help.

M.

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

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

发布评论

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

评论(1

多孤肩上扛 2024-12-06 09:05:02

\A 匹配字符串的开头,如果该位置之前没有连字符,则后面的lookbehind 匹配。

你在字符串的开头,当然前面没有字符!

请改用负向前瞻:(?![\d\-])

字符串末尾的情况类似。您必须使用负向后查找来代替 (?。

我认为与您当前的表达式等效的表达式是:

DOMAIN_LABEL_RE = """
(?i               # case insensitive
  \A(
    ([a-z])       # need at least 1 letter and cannot start with digit or hyphen
    ([a-z\d-]*?)
    (?<!-)        # cannot end with a hyphen
  )\Z
)
"""

注意: 我没有检查该表达式是否确实适合您要解决的问题。

\A matches the start of the string and the following lookbehind matches if there is no hyphen before that position.

You are at the beginning of the string, of course there is no character before it!

Use a negative lookahead instead: (?![\d\-]).

Similar for the end of the string. You have to use a negative lookbehind instead (?<!\-).

I think an equivalent expressions to your current one would be:

DOMAIN_LABEL_RE = """
(?i               # case insensitive
  \A(
    ([a-z])       # need at least 1 letter and cannot start with digit or hyphen
    ([a-z\d-]*?)
    (?<!-)        # cannot end with a hyphen
  )\Z
)
"""

Note: I did not check whether the expression is actually suited for the problem you are trying to solve.

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