2017-09-15 13 views
1

주 도메인에서 문자열과 그 하위 도메인을 추출하려고합니다. 예를 들어
는 주 도메인 example.co 내가 원하는에 :문자열에서 여러 FQDN을 구문 분석

  • 추출물만을 주 도메인과 하위 도메인 - example.co, www.example.co, 오른쪽으로 확장 uat.smile.example.co
  • 픽업 이름이 아닌 - 아니 www.example.com, www.example.co.nz
  • 는 구분

Curre 같은 FQDN 법적 아닌 모든 공백이나 구두점 문자를 무시 ntly 내가 원치 않는 항목을 얻고있다 :
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 '] 

정규 표현식을 사용해야합니까? 그렇다면,이를 통해 일하는 것에 대한 지침은 많은 것을 인정할 것입니다.
그렇지 않으면 작업을위한 더 나은 도구가 있습니까?

편집 - 검증 마크 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) 코드는 빈 목록을 반환합니다.

+0

정규 표현식이 좋은 보편적 정규식의

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

설명합니다. – Acepcs

+0

정규 표현식은'((? : [a-zA-Z] [- \ w] * \.) * {} (?! \ w))'입니다.'서브 도메인이 단지 하나의 문자를 가질 수 있거나, 전혀 없어. –

+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 

는 결과로 제공합니다

(     # 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 
+0

그리고 약간의 설명이 우리에게 더 도움이 될 것입니다. +1 : –

+0

대단히 감사합니다. –

+0

rfc 1034. 하위 도메인을 문자로 시작해야합니다. –