2015-02-02 4 views
1

나는파이썬 정규식 - 하위 문자열 일치

pattern = "hello" 

및 문자열

str = "good morning! hello helloworld" 

싶습니다 패턴이 전체 문자열이 정상적으로 즉 단어로 존재 함을 str 등의 pattern을 검색해야 서브 문자열 hellohelloworld에 넣지 마십시오. str에 hello이 없으면 False를 반환해야합니다.

정규식 패턴을 찾고 있습니다.

+0

난 당신이 여기에 답변을 찾을 것이라고 생각 : https://stackoverflow.com/questions/5717886/extracting-whole-words –

답변

2

이 작업에 정규 표현식을 사용하려는 경우 검색하려는 패턴 주변에서 단어 경계를 사용할 수 있습니다.

>>> import re 
>>> pattern = re.compile(r'\bhello\b', re.I) 
>>> mystring = 'good morning! hello helloworld' 
>>> bool(pattern.search(mystring)) 
True 
2

\b 경기 시작하거나 단어의 끝.

그래서 패턴은 하나의 일치, re.search() 반환 없음 또는 ( .group() 리턴 매치 정확한 문자열을 사용하여) 클래스 타입의 객체를 찾고 있습니다 가정 pattern = re.compile(r'\bhello\b')

될 것이다.

일치하는 항목이 여러 개있는 경우 re.findall()이 필요합니다. 일치 목록 (일치하지 않는 빈 목록)을 반환합니다.

전체 코드 :

import re 

str1 = "good morning! hello helloworld" 
str2 = ".hello" 

pattern = re.compile(r'\bhello\b') 

try: 
    match = re.search(pattern, str1).group() 
    print(match) 
except AttributeError: 
    print('No match')