Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Regex를 사용하여 Python에서 패턴 일치

<시간/>

정규 표현식이란 무엇입니까?

현실 세계에서 대부분의 프로그래밍 언어에서 문자열 구문 분석은 정규식으로 처리됩니다. 파이썬 프로그래밍 언어의 정규식은 텍스트 패턴을 일치시키는 데 사용되는 방법입니다.

모든 Python 설치와 함께 제공되는 "re" 모듈은 정규식 지원을 제공합니다.

파이썬에서 정규 표현식 검색은 일반적으로 다음과 같이 작성됩니다.

match = re.search(pattern, string)

re.search() 메서드는 정규식 패턴과 문자열의 두 인수를 사용하여 문자열 내에서 해당 패턴을 검색합니다. 패턴이 문자열 내에서 발견되면 search()는 일치 개체를 반환하고 그렇지 않으면 None을 반환합니다. 따라서 정규식에서 문자열이 지정되면 해당 문자열이 지정된 패턴과 일치하는지 확인하고 선택적으로 관련 정보가 포함된 하위 문자열을 수집합니다. 정규 표현식을 사용하여 다음과 같은 질문에 답할 수 있습니다. -

  • 이 문자열이 유효한 URL입니까?

  • /etc/passwd의 어떤 사용자가 주어진 그룹에 있습니까?

  • 로그 파일에 있는 모든 경고 메시지의 날짜와 시간은 어떻게 됩니까?

  • 방문자가 입력한 URL이 요청한 사용자 이름과 문서는 무엇입니까?

일치하는 패턴

정규식은 복잡한 미니 언어입니다. 알 수 없는 문자열과 일치시키기 위해 특수 문자에 의존하지만 항상 자신과 일치하는 문자, 숫자 및 공백 문자와 같은 리터럴 문자부터 시작하겠습니다. 기본 예를 살펴보겠습니다.

#Need module 're' for regular expression
import re
#
search_string = "TutorialsPoint"
pattern = "Tutorials"
match = re.match(pattern, search_string)
#If-statement after search() tests if it succeeded
if match:
   print("regex matches: ", match.group())
else:
   print('pattern not found')

결과

regex matches: Tutorials

문자열 일치

파이썬의 "re" 모듈에는 수많은 메소드가 있으며 특정 정규식이 특정 문자열과 일치하는지 테스트하려면 re.search()를 사용할 수 있습니다. re.MatchObject는 일치하는 문자열 부분이 발견된 것과 같은 추가 정보를 제공합니다.

구문

matchObject = re.search(pattern, input_string, flags=0)

예시

#Need module 're' for regular expression
import re
# Lets use a regular expression to match a date string.
regex = r"([a-zA-Z]+) (\d+)"
if re.search(regex, "Jan 2"):
   match = re.search(regex, "Jan 2")
   # This will print [0, 5), since it matches at the beginning and end of the
   # string
   print("Match at index %s, %s" % (match.start(), match.end()))
   # The groups contain the matched values. In particular:
   # match.group(0) always returns the fully matched string
   # match.group(1), match.group(2), ... will return the capture
   # groups in order from left to right in the input string  
   # match.group() is equivalent to match.group(0)
   # So this will print "Jan 2"
   print("Full match: %s" % (match.group(0)))
   # So this will print "Jan"
   print("Month: %s" % (match.group(1)))
   # So this will print "2"
   print("Day: %s" % (match.group(2)))
else:
   # If re.search() does not match, then None is returned
   print("Pattern not Found! ")

결과

Match at index 0, 5
Full match: Jan 2
Month: Jan
Day: 2

위의 방법은 첫 번째 일치 후에 중지되므로 데이터를 추출하는 것보다 정규식을 테스트하는 데 더 적합합니다.

그룹 캡처

패턴에 두 개 이상의 괄호가 포함된 경우 최종 결과는 괄호() 그룹 메커니즘 및 finall()의 도움으로 문자열 목록 대신 튜플이 됩니다. 일치하는 각 패턴은 튜플로 표시되며 각 튜플에는 group(1), group(2).. 데이터가 포함됩니다.

import re
regex = r'([\w\.-]+)@([\w\.-]+)'
str = ('hello john@hotmail.com, hello@Tutorialspoint.com, hello python@gmail.com')
matches = re.findall(regex, str)
print(matches)
for tuple in matches:
   print("Username: ",tuple[0]) #username
   print("Host: ",tuple[1]) #host

결과

[('john', 'hotmail.com'), ('hello', 'Tutorialspoint.com'), ('python', 'gmail.com')]
Username: john
Host: hotmail.com
Username: hello
Host: Tutorialspoint.com
Username: python
Host: gmail.com

문자열 찾기 및 바꾸기

또 다른 일반적인 작업은 주어진 문자열에서 패턴의 모든 인스턴스를 검색하고 교체하는 것입니다. re.sub(pattern, replacement, string)은 정확히 그 작업을 수행합니다. 예를 들어 이전 이메일 도메인의 모든 인스턴스를 교체하려면

코드

# requid library
import re
#given string
str = ('hello john@hotmail.com, hello@Tutorialspoint.com, hello python@gmail.com, Hello World!')
#pattern to match
pattern = r'([\w\.-]+)@([\w\.-]+)'
#replace the matched pattern from string with,
replace = r'\1@XYZ.com'
   ## re.sub(pat, replacement, str) -- returns new string with all replacements,
   ## \1 is group(1), \2 group(2) in the replacement
print (re.sub(pattern, replace, str))

결과

hello john@XYZ.com, hello@XYZ.com, hello python@XYZ.com, Hello World!

재 옵션 플래그

위와 같은 파이썬 정규식에서 패턴 일치의 동작을 수정하기 위해 다른 옵션을 사용할 수 있습니다. 이러한 추가 인수, 선택적 플래그는 search() 또는 findall() 등의 함수에 추가됩니다(예:re.search(pattern, string, re.IGNORECASE)).

  • 무시 -

    이름에서 알 수 있듯이 패턴을 대/소문자를 구분하지 않고 'a'와 'A'가 포함된 문자열이 모두 일치합니다.

  • re.DOTALL은 dot(.) 메타 문자가 개행(\n)을 포함한 모든 문자와 일치하도록 허용합니다.

  • 멀티라인

    re.MULTILINE을 사용하면 문자열의 각 줄의 시작(^) 및 끝($)을 일치시킬 수 있습니다. 그러나 일반적으로 ^ 및 &는 전체 문자열의 시작과 끝과 일치합니다.