본문 바로가기

언어/Python

[ Python ] match() 사용시 Greedy vs Non-Greedy 설명과 예제

반응형

파이썬에서 정규 표현식(regex)을 사용할 때, greedynon-greedy 매칭 방식의 차이는 매우 중요합니다. 이 두 가지 방식은 패턴이 가능한 한 많이 혹은 적게 매칭되는지를 결정합니다.

1. Greedy (탐욕적) 매칭

Greedy 매칭은 가능한 한 많이 매칭하려고 시도합니다. 기본적으로 정규 표현식의 메타 문자 *, +, ? 등은 greedy 방식입니다.

예:

  • 패턴 .*는 가능한 한 많은 문자를 매칭합니다.

2. Non-Greedy (비탐욕적) 매칭

Non-Greedy 매칭은 가능한 한 적게 매칭하려고 시도합니다. 메타 문자 뒤에 ?를 붙여서 non-greedy 방식으로 만들 수 있습니다.

예:

  • 패턴 .*?는 가능한 한 적은 문자를 매칭합니다.

3. 예제

다음은 greedynon-greedy 매칭의 차이를 보여주는 예제입니다:

import re

text = "This is a sample text. This is another sample text."

# Greedy 매칭
greedy_pattern = re.compile(r'This.*text')
greedy_match = greedy_pattern.search(text)

# Non-Greedy 매칭
non_greedy_pattern = re.compile(r'This.*?text')
non_greedy_match = non_greedy_pattern.search(text)

print("Greedy Match:")
print(greedy_match.group())  # This is a sample text. This is another sample text.

print("\nNon-Greedy Match:")
print(non_greedy_match.group())  # This is a sample text.

4. 설명

  • greedy_patternThistext 사이에 있는 가능한 모든 문자를 매칭하려고 시도합니다. 따라서 문자열 전체를 매칭합니다.
  • non_greedy_patternThistext 사이에 있는 가능한 최소한의 문자를 매칭하려고 시도합니다. 따라서 첫 번째 This와 첫 번째 text 사이의 부분만 매칭합니다.

이 차이는 정규 표현식을 사용할 때 원하는 매칭 결과를 얻기 위해 매우 중요합니다. greedynon-greedy 방식을 적절히 사용하여 정확한 매칭을 얻을 수 있습니다.

반응형