【问题标题】:Parsing several FQDNs from string从字符串中解析几个 FQDN
【发布时间】:2023-03-12 03:31:02
【问题描述】:

给定一个主域,我试图从一个字符串中提取它及其子域。
例如对于主域example.co 我想:

  • 仅提取主域和子域 - example.cowww.example.couat.smile.example.co
  • 不是向右延伸的拾音器名称 - 没有 www.example.comwww.example.co.nz
  • 忽略 FQDN 中任何不合法的空格或标点符号作为分隔符

目前我从以下地址收到不需要的物品:
example.com
example.co.nz
test-me.www.example.co 还包括尾随空格。

>>> domain = 'example\.co'
>>> line = 'example.com example.co.nz www.example.co. test-me.www.example.co bad.example-co.co'
>>> re.findall("[^\s\',]*{}[\s\'\,]*".format(domain), line)
['example.co', 'example.co', 'www.example.co', 'test-me.www.example.co ']

我应该使用正则表达式吗?如果是这样,我们将非常感谢您提供有关解决此问题的指导。
否则有没有更好的工具来完成这项工作?

编辑 - 已验证 Marc Lambrichs 的回答,但在以下情况下失败:

import re

pattern = r"((?:[a-zA-Z][\w-]+\.)+{}(?!\w))"
domain = 'google.com'
line = 'google.com mail is handled by 20 alt1.aspmx.l.google.com.'
results = re.findall(pattern.format(re.escape(domain)), line)
print(results)
[]  

另外,我想传递像“google.com”这样的字符串而不是“google.com”并使用re 转义,但re.escape(domain) 代码以任何方式返回空列表。

【问题讨论】:

  • 正则表达式好通用。
  • 正则表达式应该是((?:[a-zA-Z][-\w]*\.)*{}(?!\w)),因为子域可以只有 1 个字母,也可以完全不存在。
  • 最后一句话——关于转义——在我的回答中的例子中得到了解决。

标签: python regex parsing fqdn


【解决方案1】:

您可以为此使用 regex,而无需进行任何拆分。

$ cat test.py
import re

tests = { 'example.co': 'example.com example.co.nz www.example.co. test-me.www.example.co bad.example-co.co',
          'google.com': 'google.com mail is handled by 20 alt1.aspmx.l.google.com.'}


pattern = r"((?:[a-zA-Z][-\w]*\.)*{}(?!\w))"

for domain,line in tests.iteritems():
    domain = domain.replace(".", "\\.")
    results = re.findall(pattern.format(domain), line)
    print results

给出结果:

$ python test.py
['google.com', 'alt1.aspmx.l.google.com']
['example.co', 'www.example.co', 'test-me.www.example.co']

解释正则表达式

(                  # group 1 start
  (?:              # non-capture group
     [a-zA-Z]      # rfc 1034. start subdomain with a letter
     [\w-]*\.      # 0 or more word chars or '-', followed by '.'
  )*               # repeat this non-capture group 0 or more times
  example.co       # match the domain
  (?!\w)           # negative lookahead: no following word char allowed.
)                  # group 1 end

【讨论】:

  • 稍微解释一下对我们会更有帮助。 +1:)
  • 检查 rfc 1034。子域应该以字母开头。
  • 感谢 Marc,特别是正则表达式故障!
  • 模式应该是pattern = r"((?:[a-zA-Z][-\w]*\.)*{}(?!\w))"。调整我的答案。
猜你喜欢
  • 2011-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-24
  • 2011-03-06
相关资源
最近更新 更多