Regular Expression (정규 표현식)
파이썬에서 정규 표현식에 사용되는 기본 라이브러리는 're 모듈' 입니다.
주로 문자열에 대한 패턴(정규식)을 사용하여 데이터로 부터 검색, 대체 등의 기능 및 가능한 방법들을 소개합니다.
1. Importing the module
import re
2. Matching Patterns
re.match() 함수는 문자열의 시작에서 패턴이 일치하는지 확인할 수 있습니다.
match = re.match(pattern, string)
Matching Patterns 예제
찾고자 하는 문자열이 현재 string 에 있는지, 파일로 부터 Line 단위로 읽은 후에 문자열이 있는지 확인할 때 사용하는 경우 유용한 함수입니다. 아래 예제에서 pattern 을 어떻게 정의하느냐에 따라 다양한 matching 을 구현할 수 있겠습니다.
pattern = r"abc"
string = "abcdef"
match = re.match(pattern, string)
if match:
print("Match found!")
else:
print("No match.")
Matching Patterns Test
그러면 갑자기 궁금해집니다. 찾고자 하는 문자열이 위치와 상관없이 matching 되는 걸까요?
위의 예제를 아래와 같이 함수로 만들고 서로 다른 입력으로 테스트해보겠습니다.
def do_matching_test(pattern, string):
match = re.match(pattern, string)
if match:
print("Match found! %s" %(string))
else:
print("No match. %s" %(string))
패턴은 동일하게 "abc", string1 은 "abcdef", 패턴으로 시작하는 문자열이고, string2 는 "defabc" 으로 패턴이 포함된 문자열을 테스트 하는 main 함수입니다.
if __name__ == '__main__':
pattern = r"abc"
string1 = "abcdef"
string2 = "defabc"
do_matching_test(pattern, string1)
do_matching_test(pattern, string2)
이 함수들을 실행해보면 결과는 다음과 같습니다. match 함수는 패턴으로 시작할 때 matching 되었다고 판단하는 함수입니다. 포함된 결과는 다음에서 설명할 search 입니다.
Match found! abcdef
No match. defabc
3. Search for patterns:
re.search() 함수는 문자열의 어느 곳에서나 패턴을 검색을 할 수 있습니다.
match = re.search(pattern, string)
Search for Patterns 예제
pattern = r"world"
string = "Hello, world!"
match = re.search(pattern, string)
if match:
print("Match found!")
else:
print("No match.")
Search for Patterns Test
위의 예제를 아래와 같이 함수로 만들고 서로 다른 입력으로 테스트해보겠습니다.
def do_searching_test(pattern, string):
match = re.search(pattern, string)
if match:
print("Found it! %s" %(string))
else:
print("No match. %s" %(string))
이번에는 패턴을 "world" 로 설정하고, "Hello, world!" 와 "Welcome to my blog.." 로 입력합니다.
if __name__ == '__main__':
pattern = r"world"
string1 = "Hello, world!"
string2 = "Welcome to my blog.."
do_searching_test(pattern, string1)
do_searching_test(pattern, string2)
결과는 "Hello, world!" 을 찾았다고 나옵니다. re.match() 의 경우, 패턴으로 시작하는 문자열만 확인이 가능하다면, re.search() 패턴과 일치하는 문자열이 포함되어 있더라도 확인이 가능한 것이 특징입니다.
Found it! Hello, world!
No match. Welcome to my blog..
4. Find All
re.findall() 함수는 문자열 내 패턴의 겹치지 않는 모든 발생을 목록으로 반환합니다.
pattern = r"\d+" # Matches one or more digits
string = "I have 123 apples and 456 bananas."
matches = re.findall(pattern, string)
print(matches) # Output: ['123', '456']
5. Replacing pattern
re.sub() 함수는 문자열에서 패턴을 지정된 대체 문자열로 대체하는 기능입니다.
pattern = r"apple"
string = "I have an apple, but I prefer oranges."
replacement = "banana"
new_string = re.sub(pattern, replacement, string)
print(new_string) # Output: "I have an banana, but I prefer oranges."
6. Pattern Object
re.compile() 함수는 정규 표현식 패턴을 패턴 객체로 컴파일하는 데 사용된다. 이어서, 패턴 객체는 매칭, 검색 및 치환과 같은 다양한 동작에 사용될 수 있습니다.
pattern_object = re.compile(pattern, flags=0)
여기서, 패턴은 컴파일하고자 하는 정규 표현식 패턴이며, 패턴 매칭의 거동을 수정하기 위해 플래그(선택 사항)가 사용됩니다. 플래그 인수는 re.IGNORECASE, re.MULTILINE, re.DOTALL 등 해당 모듈에서 제공하는 다양한 플래그 상수의 비트별 OR이며, 비트별 OR 연산자(|)와 결합하여 여러 개의 플래그를 사용할 수 있습니다.
re.compile()을 사용하면 정규 표현식 패턴을 미리 컴파일하여 여러 번 재사용할 수 있어 패턴 매칭 연산의 성능을 향상시킬 수 있습니다. 결과적인 패턴 객체는 match(), search(), findall(), sub() 등의 방법을 가지며, 이는 패턴 객체 상에서 직접 호출될 수 있습니다.
import re
pattern = r"apple"
flags = re.IGNORECASE # Ignore case while matching
# Compile the pattern
pattern_object = re.compile(pattern, flags)
# Perform matching
string = "I have an Apple and an APPLE"
match = pattern_object.search(string)
if match:
print("Match found!")
else:
print("No match.")
이 예제에서는 패턴 r"apple"을 re.IGNORECASE 플래그와 컴파일하여 대소문자를 구분하지 않는 매칭을 허용합니다. 이어서, 결과적인 패턴 객체는 주어진 스트링 내의 패턴을 검색하는 데 사용된다. search() 방법은 패턴 객체(pattern_object) 상에서 호출되어 검색 동작을 수행합니다.
정규 표현식은 문자열의 패턴을 조작하고 검색하는 강력한 방법을 제공합니다. 사용 가능한 기능과 구문에 대한 보다 발전된 사용 및 정보는 해당 모듈의 공식 파이썬 문서를 참조하시면 도움이 될 수 있습니다.
7. Method Overview
re module 의 주요 Method 를 정리해보았습니다.
Function/Method | Description |
re.match() | Determines if the pattern matches at the beginning of the string. |
re.search() | Searches the string for a match to the pattern. Returns the first match found. |
re.findall() | Returns all non-overlapping matches of the pattern in the string as a list. |
re.finditer() | Returns an iterator yielding match objects for all non-overlapping matches of the pattern in the string. |
re.sub() | Replaces all occurrences of the pattern in the string with a specified replacement. |
re.split() | Splits the string by the occurrences of the pattern and returns a list of substrings. |
match.group([group1, ...]) | Returns one or more subgroups of the match. If no arguments are provided, returns the entire match. |
match.start([group]) | Returns the starting index of the match or a specific group within the match. |
match.end([group]) | Returns the ending index (one index after the last character) of the match or a specific group within the match. |
match.span([group]) | Returns a tuple containing the start and end indices of the match or a specific group within the match. |
re.compile() | Compiles a regular expression pattern into a pattern object. The resulting pattern object can be used for various operations. |
8. Pattern Overview
주로 사용되는 Pattern 을 정리해보았습니다.
Pattern | Description |
. | Matches any character except a newline. |
^ | Matches the start of a string. |
$ | Matches the end of a string. |
\A | Matches only at the start of a string. |
\Z | Matches only at the end of a string. |
[abc] | Matches any single character from the given set. |
[^abc] | Matches any single character that is not in the given set. |
[0-9] | Matches any digit from 0 to 9. |
\d | Matches any digit (equivalent to [0-9]). |
\D | Matches any non-digit character. |
\w | Matches any alphanumeric character (word character). |
\W | Matches any non-alphanumeric character. |
\s | Matches any whitespace character (space, tab, newline, etc.). |
\S | Matches any non-whitespace character. |
* | Matches zero or more occurrences of the preceding pattern. |
+ | Matches one or more occurrences of the preceding pattern. |
? | Matches zero or one occurrence of the preceding pattern. |
{n} | Matches exactly n occurrences of the preceding pattern. |
{n,} | Matches n or more occurrences of the preceding pattern. |
{n,m} | Matches between n and m occurrences of the preceding pattern. |
(...) | Creates a capturing group. The matched substring can be extracted using .group() method. |
(?P<name>...) | Creates a named capturing group. The matched substring can be extracted using .group('name') method. |
(?i) | Enables case-insensitive matching. |
(?m) | Enables multi-line mode, where ^ and $ match the start and end of each line. |
(?s) | Enables dot-all mode, where . matches any character, including a newline. |
(?x) | Enables verbose mode, allowing whitespace and comments within the pattern. |
이상입니다.
읽어주셔서 감사합니다. 잘못된 내용을 발견하거나 추가할 내용이 생기면 업데이트 될 수 있습니다.
'IT > Python' 카테고리의 다른 글
Python 파이썬으로 String 문자열 처리 (0) | 2023.06.23 |
---|---|
Python 파이썬으로 HTML 다루기 - BeautifulSoup (0) | 2023.06.21 |
Python 파이썬으로 Excel 다루기 - openpyxl (0) | 2023.06.18 |
Python 파이썬 기본 문법 (0) | 2023.06.18 |
Python 파이썬 프로그래밍 소개 (0) | 2023.06.18 |