기술(Tech, IT)/파이썬(Python)

[Tech, Python] re.group()

Daniel803 2024. 3. 13. 05:31

re.group() 함수는 검색된 패턴에서 일치하는 항목을 가져오는 데 사용된다. 이 함수는 정규식과 일치하는 문자열의 일부를 추출하는 데 사용할 수 있다. 예시를 살펴보자.

 

  1. 기본 사용법
    import re
    
    # Compile a pattern and search in the string
    pattern = re.compile(r'\d+')  # Matches one or more digits
    match = pattern.search('The price is 123 dollars.')
    
    # Use group to get the matched string
    if match:
        print(match.group())  # Output: 123​
  2. 괄호를 사용해 일치하는 문자열 중 특정 문자열 접근
    import re
    
    text = "John's phone number is 123-456-7890."
    pattern = re.compile(r'(\d{3})-(\d{3})-(\d{4})')
    
    match = pattern.search(text)
    
    if match:
        print("Full match:", match.group())  # Output: 123-456-7890
        print("Area code:", match.group(1))  # Output: 123
        print("Prefix:", match.group(2))     # Output: 456
        print("Line number:", match.group(3))  # Output: 7890​
  3. 이름을 활용한 접근
    import re
    
    text = "John's phone number is 123-456-7890."
    pattern = re.compile(r'(?P<area>\d{3})-(?P<prefix>\d{3})-(?P<line>\d{4})')
    
    match = pattern.search(text)
    
    if match:
        print("Full match:", match.group())     # Output: 123-456-7890
        print("Area code:", match.group('area'))  # Output: 123
        print("Prefix:", match.group('prefix'))   # Output: 456
        print("Line number:", match.group('line'))  # Output: 7890

re.group() 의 인덱스는 1부터 시작된다는 점에 유의해야 한다. 또한 패턴 내에 두 개 이상의 regex가 존재하지만 일치하는 문자열을 찾지 못했을 경우 'None' 혹은 "" (empty string, 빈 문자열)이 할당된다. 'None'이 할당되는 경우는 '\w+' 처럼 '+'를 통해 1개 이상이 일치했을 때 할당되며, "" (empty string, 빈 문자열)은 '\w*' 처럼 '*'를 사용해 0개 이상의 일치를 찾을 때 할당된다. (다른 방법으로 해석하자면 '*'를 사용해 찾는다는 것은 일치하는 것이 0개라도 일단 일치한다고 인식하는 걸로 이해해도 된다.

 

참고

- https://docs.python.org/3/howto/regex.html

- https://blog.naver.com/hankrah/222323782668

'기술(Tech, IT) > 파이썬(Python)' 카테고리의 다른 글

[Tech, Python] main method  (0) 2024.03.15
[Tech, Python] \b (정규식)  (0) 2024.03.14
[Tech, Python] re.compile()  (0) 2024.03.08
[Tech, Python] re.escape  (0) 2024.03.02
[Python] raw strings  (0) 2024.01.07