Python RegEx: re.match(), re.search(), re.findall()(예제 포함)
⚡ 스마트 요약
Python 정규 표현식 튜토리얼에서는 실제 예제를 통해 re.match, re.search, re.findall 및 re.split 함수를 다룹니다. Lessons는 메타 문자, 문자 클래스, 그룹, 플래그, 대체 및 텍스트 구문 분석 및 유효성 검사를 위한 일반적인 패턴을 설명합니다.
정규 표현식이란 무엇입니까? Python?
A 정규식(RE) 프로그래밍 언어에서 `search`는 검색 패턴을 설명하는 데 사용되는 특수한 텍스트 문자열입니다. 이는 예를 들어 매우 유용합니다.trac코드, 파일, 로그, 스프레드시트 또는 문서와 같은 텍스트에서 정보를 추출합니다.
를 사용하는 동안 Python 정규식 가장 먼저 인식해야 할 것은 모든 것이 본질적으로 문자이며 문자열이라고도 하는 특정 문자 시퀀스와 일치하는 패턴을 작성한다는 것입니다. Ascii 또는 라틴 문자는 키보드에 있는 문자이며 유니코드는 외국 텍스트를 일치시키는 데 사용됩니다. 여기에는 숫자와 구두점, $#@!% 등의 모든 특수 문자가 포함됩니다.
예를 들어, Python 정규식은 프로그램이 문자열에서 특정 텍스트를 검색한 다음 그에 따라 결과를 인쇄하도록 지시할 수 있습니다. 표현에는 다음이 포함될 수 있습니다.
- 텍스트 매칭
- 되풀이
- 가지
- 패턴구성 등
정규식 또는 RegEx Python RE(RE, 정규식 또는 정규식 패턴)로 표시됩니다. 다시 모듈. Python 라이브러리를 통해 정규식을 지원합니다. 정규식 Python 등 다양한 것을 지원합니다. 수정자, 식별자 및 공백 문자.
| 식별자 | 수정 자 | 공백 문자 | 탈출 필요 |
|---|---|---|---|
| \d= 임의의 숫자(숫자) | \d는 숫자를 나타냅니다. 예: \d{1,5} 1,5 등과 같이 424,444,545 사이의 숫자를 선언합니다. | \n = 새 줄 | . + * ? [] $ ^ () {} | \ |
| \D= 숫자가 아닌 것(숫자가 아닌 것) | + = 1개 이상 일치 | \s= 공백 | |
| \s = 공백 (탭, 공백, 개행 등) |
? = 0 또는 1과 일치 | \t =탭 | |
| \S= 공백이 아닌 것 | * = 0 이상 | \e = 탈출 | |
| \w = letters ( Match alphanumeric character, including "_") | $ 문자열의 끝과 일치 | \r = 캐리지 리턴 | |
| \W =anything but letters ( Matches a non-alphanumeric character excluding "_") | ^ 문자열의 시작과 일치 | \f= 폼피드 | |
| . = 문자(마침표)를 제외한 모든 것 | | 또는 x/y와 일치 | ----------------- | |
| \b = 개행을 제외한 모든 문자 | [] = range or "variance" | ---------------- | |
| \. | {x} = 이전 코드의 양 | ----------------- |
정규식(RE) 구문
import re
- "re" module included with Python 주로 문자열 검색 및 조작에 사용됨
- Also used frequently for web page "스크 라ping" (extrac(웹사이트에서 가져온 대량의 데이터)
(w+) 및 (^) 표현식을 사용하는 간단한 연습으로 표현식 튜토리얼을 시작하겠습니다.
w+ 및 ^ 표현식의 예
- "^": 이 표현식은 문자열의 시작과 일치합니다.
- "w+": This expression matches the alphanumeric character in the string
여기에서 우리는 Python RegEx 코드에서 w+ 및 ^ 표현식을 사용하는 방법의 예입니다. re.findall() 함수를 다음에서 다룹니다. Python, 이 튜토리얼의 후반부에서 다루겠지만 당분간은 \w+와 \^ 표현식에만 집중하겠습니다.
For example, for our string "guru99, education is fun" if we execute the code with w+ and^, it will give the output "guru99".
import re xx = "guru99,education ">is fun" r1 = re.findall(r"^\w+",xx) print(r1)
w+에서 +부호를 제거하면 출력이 변경되고 첫 글자의 첫 번째 문자, 즉 [g]만 제공됩니다.
re.split 함수의 \s 표현식 예
- "s": This expression is used for creating a space in the string
이 RegEx가 어떻게 작동하는지 이해하려면 Python 작동하면 간단한 것부터 시작합니다. Python RegEx Example of a split function. In the example, we have split each word using the "re.split" function and at the same time we have used expression \s that allows to parse each word in the string separately.
When you execute this code it will give you the output ['we', 'are', 'splitting', 'the', 'words'].
Now, let see what happens if you remove "\" from s. There is no 's' alphabet in the output, this is because we have removed '\' from the string, and it evaluates "s" as a regular character and thus split the words wherever it finds "s" in the string.
마찬가지로 다른 시리즈도 있어요 Python 다양한 방법으로 사용할 수 있는 정규 표현식 Python \d,\D,$,\.,\b 등과 같은
다음은 완전한 코드입니다.
import re xx = "guru99,education ">is fun" r1 = re.findall(r"^\w+", xx) print((re.split(r'\s','we are splitting the words'))) print((re.split(r's','split the words')))
다음으로 정규 표현식과 함께 사용되는 메소드 유형을 살펴보겠습니다. Python.
정규식 방법 사용
The "re" package provides several methods to actually perform queries on an input string. We will see the methods of re in Python:
- 다시 일치()
- 연구()
- re.findall()
주의 사항: 정규식을 기반으로, Python 두 가지 다른 기본 연산을 제공합니다. match 메서드는 문자열의 시작 부분에서만 일치 항목을 검사하는 반면 search는 문자열의 어느 곳에서나 일치 항목을 검사합니다.
다시 일치()
다시 일치() re의 기능 Python 정규식 패턴을 검색하고 첫 번째 항목을 반환합니다. 그만큼 Python RegEx Match 메서드는 문자열 시작 부분에서만 일치 항목을 확인합니다. 따라서 첫 번째 줄에서 일치 항목이 발견되면 일치 개체를 반환합니다. 그러나 다른 줄에서 일치하는 항목이 발견되면 Python RegEx Match 함수는 null을 반환합니다.
예를 들어, 다음 코드를 고려하십시오. Python re.match() function. The expression "w+" and "\W" will match the words starting with letter 'g' and thereafter, anything which is not started with 'g' is not identified. To check match for each element in the list or string, we run the forloop in this Python re.match() 예.
re.search(): 텍스트에서 패턴 찾기
연구() 함수는 정규식 패턴을 검색하고 첫 번째 항목을 반환합니다. 같지 않은 Python re.match(), 입력 문자열의 모든 줄을 확인합니다. 그만큼 Python re.search() 함수는 패턴이 발견되면 일치 객체를 반환하고, 패턴이 발견되지 않으면 "null"을 반환합니다.
검색()을 어떻게 사용하나요?
search() 기능을 사용하려면 import를 해야 합니다. Python 먼저 모듈을 다시 만든 다음 코드를 실행하세요. 그만큼 Python re.search() function takes the "pattern" and "text" to scan from our main string
For example here we look for two literal strings "Software testing" "guru99", in a text string "Software 지원 is fun". For "software testing" we found the match hence it returns the output of Python re.search() Example as "found a match", while for word "guru99" we could not found in string hence it returns the output as "No match".
re.findall()
찾기() `findall` 모듈은 주어진 패턴과 일치하는 모든 항목을 검색하는 데 사용됩니다. 이와 대조적으로 `search()` 모듈은 지정된 패턴과 일치하는 첫 번째 항목만 반환합니다. `findall` 모듈은 파일의 모든 줄을 순회하며 겹치지 않는 모든 항목을 반환합니다.ping 한 번에 패턴 일치.
re.findall()을 사용하는 방법 Python?
여기에는 이메일 주소 목록이 있으며 목록에서 모든 이메일 주소를 가져오려면 re.findall() 메서드를 사용합니다. Python. 목록에서 모든 이메일 주소를 찾습니다.
re.findall() 예제의 전체 코드는 다음과 같습니다.
import re list = ["guru99 get", "guru99 give", "guru Selenium"] for element in list: z = re.match("(g\w+)\W(g\w+)", element) if z: print((z.groups())) patterns = ['software testing', 'guru99'] text = 'software testing is fun?' for pattern in patterns: print('Looking for "%s" in "%s" ->' % (pattern, text), end=' ') if re.search(pattern, text): print('found a match!') else: print('no match') abc = 'guru99@google.com, careerguru99@hotmail.com, users@yahoomail.com' emails = re.findall(r'[\w\.-]+@[\w\.-]+', abc) for email in emails: print(email)
Python 깃발
많은 Python Regex 메소드 및 Regex 함수는 Flags라는 선택적 인수를 사용합니다. 이 플래그는 주어진 의미를 수정할 수 있습니다. Python 정규식 패턴. 이를 이해하기 위해 이러한 플래그의 한두 가지 예를 살펴보겠습니다.
다양한 플래그가 사용됨 Python 포함
| 정규식 플래그 구문 | 이 깃발의 역할은 무엇입니까? |
|---|---|
| [리엠] | 각 줄의 시작/끝을 고려하세요. |
| [재.I] | 대소문자를 무시합니다. |
| [re.S] | 만들다 [ . ] |
| [re.U] | { \w,\W,\b,\B}가 유니코드 규칙을 따르도록 만드세요. |
| [re.L] | {\w,\W,\b,\B}가 로케일을 따르도록 설정 |
| [리엑스] | Regex에서 주석 허용 |
re.M 또는 여러 줄 플래그의 예
In multiline the pattern character [^] match the first character of the string and the beginning of each line (following immediately after the each newline). While expression small "w" is used to mark the space with characters. When you run the code the first variable "k1" only prints out the character 'g' for word guru99, while when you add multiline flag, it fetches out first characters of all the elements in the string.
다음은 코드입니다.
import re xx = """guru99 careerguru99 selenium""" k1 = re.findall(r"^\w", xx) k2 = re.findall(r"^\w", xx, re.MULTILINE) print(k1) print(k2)
- We declared the variable xx for string " guru99…. careerguru99….selenium"
- Run the code without using flags multiline, it gives the output only 'g' from the lines
- Run the code with flag "multiline", when you print 'k2' it gives the output as 'g', 'c' and 's'
- 따라서 위의 예에서 여러 줄을 추가한 후와 추가하기 전의 차이점을 확인할 수 있습니다.
마찬가지로 다른 것도 사용할 수 있습니다 Python re.U(유니코드), re.L(로케일 따르기), re.X(주석 허용) 등과 같은 플래그
Python 2 예
위의 코드는 Python 3가지 예, 실행하고 싶다면 Python 2 다음 코드를 고려해 보세요.
# Example of w+ and ^ Expression import re xx = "guru99,education ">is fun" r1 = re.findall(r"^\w+",xx) print r1 # Example of \s expression in re.split function import re xx = "guru99,education ">is fun" r1 = re.findall(r"^\w+", xx) print (re.split(r'\s','we are splitting the words')) print (re.split(r's','split the words')) # Using re.findall for text import re list = ["guru99 get", "guru99 give", "guru Selenium"] for element in list: z = re.match("(g\w+)\W(g\w+)", element) if z: print(z.groups()) patterns = ['software testing', 'guru99'] text = 'software testing is fun?' for pattern in patterns: print 'Looking for "%s" in "%s" ->' % (pattern, text), if re.search(pattern, text): print 'found a match!' else: print 'no match' abc = 'guru99@google.com, careerguru99@hotmail.com, users@yahoomail.com' emails = re.findall(r'[\w\.-]+@[\w\.-]+', abc) for email in emails: print email # Example of re.M or Multiline Flags import re xx = """guru99 careerguru99 selenium""" k1 = re.findall(r"^\w", xx) k2 = re.findall(r"^\w", xx, re.MULTILINE) print k1 print k2
테스트 Python 지식 습득
1. 문자열에서 패턴의 모든 발생을 찾는 데 사용되는 방법은 무엇입니까?
- 연구()
- 다시 일치()
- re.findall()
- 다시 분할()
2. 정규 표현식에서 \d 문자 클래스는 무엇을 나타냅니까?
- 모든 숫자 (0-9)
- 숫자가 아닌 문자
- 모든 공백 문자
- 모든 문자 또는 숫자
3. 공백을 기준으로 문자열을 분할하려면 어떤 함수를 사용할까요?
- re.split(r'\s', string)
- re.findall(r'\w+', string)
- re.match(r'\s+', string)
- re.split(r'\w+', string)
4. re.match()와 re.search()의 주요 차이점은 무엇입니까?
- re.match()는 문자열의 시작부분에서 패턴을 찾는 반면, re.search()는 문자열의 어느 곳에서나 패턴을 찾습니다.
- re.match()는 모든 일치 항목을 반환하는 반면, re.search()는 첫 번째 일치 항목을 반환합니다.
- re.search()는 re.match()보다 빠릅니다.
- 두 함수는 같은 방식으로 작동합니다.








