从字符串中解析几个FQDN

时间:2017-09-15 03:33:39

标签: python regex parsing fqdn

鉴于主域名,我试图从字符串中提取它及其子域 例如,对于主域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)代码会以任意方式返回空列表。

1 个答案:

答案 0 :(得分:2)

您可以使用正则表达式,而不会有任何分裂。

$ 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