Python의 RegEx 정규식을 사용하는 방법
RegEx 또는 정규식은 검색 패턴을 형성하는 일련의 문자입니다.
RegEx를 사용하면 문자열에 지정된 검색 패턴이 포함되어 있는지 확인할 수 있습니다.
RegEx 모듈
Python은 정규식을 처리하는 데 사용할 수 있는 re라는 내장 패키지를 제공합니다.
re 모듈 가져오기:
import re
RegEx in Python
re 모듈을 가져온 후에는 정규식을 사용할 수 있습니다.
Example
문자열을 검색하여 "China"로 시작하는지 확인하고 "country"로 끝남:
import re txt = "China is a great country" x = re.search("^China.*country$", txt)
실행 중인 인스턴스
import re txt = "China is a great country" x = re.search("^China.*country$", txt) if (x): print("YES! We have a match!") else: print("No match")
RegEx 함수
re 모듈은 일치를 위해 문자열을 검색할 수 있는 함수 세트를 제공합니다.
메타 문자
메타 문자는 다음과 같습니다.
문자: [] 설명: 문자 예 세트: "[a-m]"
import re str = "The rain in Spain" #Find all lower case characters alphabetically between "a" and "m": x = re.findall("[a-m]", str) print(x)
예제 실행
문자: 설명: 특수 시퀀스를 나타냅니다(이스케이프에도 사용할 수 있음) 특수 문자) 예: "d"
import re str = "That will be 59 dollars" #Find all digit characters: x = re.findall("\d", str) print(x)
Run 예
문자: . 설명: 모든 문자(줄 바꿈 제외) 예: "he…o"
import re str = "hello world" #Search for a sequence that starts with "he", followed by two (any) characters, and an "o": x = re.findall("he..o", str) print(x)
Run 예
문자: ^ 설명 : 시작 예: "^hello"
import re str = "hello world" #Check if the string starts with 'hello': x = re.findall("^hello", str) if (x): print("Yes, the string starts with 'hello'") else: print("No match")
Run the example
문자: $ 설명: 끝 예: "world$"
import re str = "hello world" #Check if the string ends with 'world': x = re.findall("world$", str) if (x): print("Yes, the string ends with 'world'") else: print("No match")
Run the example
문자: * 설명: 0 이상 발생 예: "aix*"
import re str = "The rain in Spain falls mainly in the plain!" #Check if the string contains "ai" followed by 0 or more "x" characters: x = re.findall("aix*", str) print(x) if (x): print("Yes, there is at least one match!") else: print("No match")
예제 실행
문자: + 설명: 하나 이상의 발생 예: "aix+"
import re str = "The rain in Spain falls mainly in the plain!" #Check if the string contains "ai" followed by 1 or more "x" characters: x = re.findall("aix+", str) print(x) if (x): print("Yes, there is at least one match!") else: print("No match")
예제 실행
문자: {} 설명 : 발생 횟수를 정확하게 지정 예: "al{2}"
import re str = "The rain in Spain falls mainly in the plain!" #Check if the string contains "a" followed by exactly two "l" characters: x = re.findall("al{2}", str) print(x) if (x): print("Yes, there is at least one match!") else: print("No match")
예제 실행
문자: | 설명: 둘 중 하나 예: "falls|stays"
import re str = "The rain in Spain falls mainly in the plain!" #Check if the string contains either "falls" or "stays": x = re.findall("falls|stays", str) print(x) if (x): print("Yes, there is at least one match!") else: print("No match")
예제 실행
문자 : ( ) 설명 : 캡처 및 그룹화
특수 시퀀스
특수 시퀀스는 아래 표의 문자 중 하나가 뒤에 오는 문자를 말하며 특별한 의미를 갖습니다.
Character: A 설명: 지정된 문자가 문자열의 시작 부분에 있으면 일치 항목을 반환합니다. 예: "AThe"
import re str = "The rain in Spain" #Check if the string starts with "The": x = re.findall("\AThe", str) print(x) if (x): print("Yes, there is a match!") else: print("No match")
예제 실행
Character: b
설명: 지정된 문자가 있는 경우 해당 문자를 반환합니다. 단어의 시작 부분에 있거나 끝 부분에 일치
예: r"bain"
import re str = "The rain in Spain" #Check if "ain" is present at the beginning of a WORD: x = re.findall(r"\bain", str) print(x) if (x): print("Yes, there is at least one match!") else: print("No match")
예제 실행
예: r"ainb"
import re str = "The rain in Spain" #Check if "ain" is present at the end of a WORD: x = re.findall(r"ain\b", str) print(x) if (x): print("Yes, there is at least one match!") else: print("No match")
예제 실행
문자 : B
설명: 일치하는 문자가 있으면 지정된 문자를 반환하지만 단어의 시작(또는 끝)에는 반환하지 않습니다.
예: r"Bain"
import re str = "The rain in Spain" #Check if "ain" is present, but NOT at the beginning of a word: x = re.findall(r"\Bain", str) print(x) if (x): print("Yes, there is at least one match!") else: print("No match")
예제 실행
예:r" ainB"
import re str = "The rain in Spain" #Check if "ain" is present, but NOT at the end of a word: x = re.findall(r"ain\B", str) print(x) if (x): print("Yes, there is at least one match!") else: print("No match")
예제 실행
문자: d
설명: 문자열에 숫자(0-9)가 포함된 일치 항목을 반환합니다.
예: "d"
import re str = "The rain in Spain" #Check if the string contains any digits (numbers from 0-9): x = re.findall("\d", str) print(x) if (x): print("Yes, there is at least one match!") else: print("No match")
예제 실행
문자: D
설명: 문자열에 숫자가 포함되지 않은 일치 항목을 반환합니다. 일치
예: "D"
import re str = "The rain in Spain" #Return a match at every no-digit character: x = re.findall("\D", str) print(x) if (x): print("Yes, there is at least one match!") else: print("No match")
예제 실행
문자: s
描述:返回字符串包含空白字符的匹配项
示例:“\s”
import re str = "The rain in Spain" #Return a match at every white-space character: x = re.findall("\s", str) print(x) if (x): print("Yes, there is at least one match!") else: print("No match")
运行示例
字符:\S
描述:返回字符串不包含空白字符的匹配项
示例:“\S”
import re str = "The rain in Spain" #Return a match at every NON white-space character: x = re.findall("\S", str) print(x) if (x): print("Yes, there is at least one match!") else: print("No match")
运行示例
字符:\w
描述: 返回一个匹配项,其中字符串包含任何单词字符 (从 a 到 Z 的字符,从 0 到 9 的数字和下划线 _ 字符)
示例:“\w”
import re str = "The rain in Spain" #Return a match at every word character (characters from a to Z, digits from 0-9, and the underscore _ character): x = re.findall("\w", str) print(x) if (x): print("Yes, there is at least one match!") else: print("No match")
运行示例
字符:\W
描述:返回一个匹配项,其中字符串不包含任何单词字符
示例:“\W”
import re str = "The rain in Spain" #Return a match at every NON word character (characters NOT between a and Z. Like "!", "?" white-space etc.): x = re.findall("\W", str) print(x) if (x): print("Yes, there is at least one match!") else: print("No match")
运行示例
字符:\Z
描述:如果指定的字符位于字符串的末尾,则返回匹配项 。
示例:“Spain\Z”
import re str = "The rain in Spain" #Check if the string ends with "Spain": x = re.findall("Spain\Z", str) print(x) if (x): print("Yes, there is a match!") else: print("No match")
运行示例
集合(Set)
集合(Set)是一对方括号 [] 内的一组字符,具有特殊含义。
字符:[arn]
描述:返回一个匹配项,其中存在指定字符(a,r 或 n)之一
示例
import re str = "The rain in Spain" #Check if the string has any a, r, or n characters: x = re.findall("[arn]", str) print(x) if (x): print("Yes, there is at least one match!") else: print("No match")
运行示例
字符:[a-n]
描述:返回字母顺序 a 和 n 之间的任意小写字符匹配项
示例
import re str = "The rain in Spain" #Check if the string has any characters between a and n: x = re.findall("[a-n]", str) print(x) if (x): print("Yes, there is at least one match!") else: print("No match")
运行示例
字符:[^arn]
描述:返回除 a、r 和 n 之外的任意字符的匹配项
示例
import re str = "The rain in Spain" #Check if the string has other characters than a, r, or n: x = re.findall("[^arn]", str) print(x) if (x): print("Yes, there is at least one match!") else: print("No match")
运行示例
字符:[0123]
描述:返回存在任何指定数字(0、1、2 或 3)的匹配项
示例
import re str = "The rain in Spain" #Check if the string has any 0, 1, 2, or 3 digits: x = re.findall("[0123]", str) print(x) if (x): print("Yes, there is at least one match!") else: print("No match")
运行示例
字符:[0-9]
描述:返回 0 与 9 之间任意数字的匹配
示例
import re str = "8 times before 11:45 AM" #Check if the string has any digits: x = re.findall("[0-9]", str) print(x) if (x): print("Yes, there is at least one match!") else: print("No match")
运行示例
字符:[0-5][0-9]
描述:返回介于 0 到 9 之间的任何数字的匹配项
示例
import re str = "8 times before 11:45 AM" #Check if the string has any two-digit numbers, from 00 to 59: x = re.findall("[0-5][0-9]", str) print(x) if (x): print("Yes, there is at least one match!") else: print("No match")
运行示例
字符:[a-zA-Z]
描述:返回字母顺序 a 和 z 之间的任何字符的匹配,小写或大写
示例
import re str = "8 times before 11:45 AM" #Check if the string has any characters from a to z lower case, and A to Z upper case: x = re.findall("[a-zA-Z]", str) print(x) if (x): print("Yes, there is at least one match!") else: print("No match")
运行示例
字符:[+]
描述:在集合中,+、*、.、|、()、$、{} 没有特殊含义,因此 [+] 表示:返回字符串中任何 + 字符的匹配项。
示例
import re str = "8 times before 11:45 AM" #Check if the string has any + characters: x = re.findall("[+]", str) print(x) if (x): print("Yes, there is at least one match!") else: print("No match")
运行示例
findall() 函数
findall() 函数返回包含所有匹配项的列表。
实例
打印所有匹配的列表
import re str = "China is a great country" x = re.findall("a", str) print(x)
运行实例
这个列表以被找到的顺序包含匹配项。
如果未找到匹配项,则返回空列表。
实例
如果未找到匹配,则返回空列表:
import re str = "China is a great country" x = re.findall("USA", str) print(x)
运行实例
search() 函数
search() 函数搜索字符串中的匹配项,如果存在匹配则返回 Match 对象。
如果有多个匹配,则仅返回首个匹配项。
实例
在字符串中搜索第一个空白字符
import re str = "China is a great country" x = re.search("\s", str) print("The first white-space character is located in position:", x.start())
运行实例
如果未找到匹配,则返回值 None:
实例
进行不返回匹配的检索
import re str = "China is a great country" x = re.search("USA", str) print(x)
运行实例
split() 函数
split() 函数返回一个列表,其中字符串在每次匹配时被拆分。
实例
在每个空白字符处进行拆分
import re str = "China is a great country" x = re.split("\s", str) print(x)
运行实例
可以通过指定 maxsplit 参数来控制出现次数:
实例
仅在首次出现时拆分字符串:
import re str = "China is a great country" x = re.split("\s", str, 1) print(x)
运行实例
sub() 函数
sub() 函数把匹配替换为您选择的文本
实例
用数字 9 替换每个空白字符
import re str = "China is a great country" x = re.sub("\s", "9", str) print(x)
运行实例
可以通过指定 count 参数来控制替换次数:
实例
替换前两次出现
import re str = "China is a great country" x = re.sub("\s", "9", str, 2) print(x)
运行实例
Match 对象
Match 对象是包含有关搜索和结果信息的对象。
注释:如果没有匹配,则返回值 None,而不是 Match 对象。
实例
执行会返回 Match 对象的搜索:
import re str = "China is a great country" x = re.search("a", str) print(x) # 将打印一个对象
运行实例
Match 对象提供了用于取回有关搜索及结果信息的属性和方法:
span()
返回的元组包含了匹配的开始和结束位置.string
返回传入函数的字符串group()
返回匹配的字符串部分
实例
打印首个匹配出现的位置(开始和结束位置)。
正则表达式查找以大写 “C” 开头的任何单词:
import re str = "China is a great country" x = re.search(r"\bC\w+", str) print(x.span())
运行实例
实例
打印传入函数的字符串
import re str = "China is a great country" x = re.search(r"\bC\w+", str) print(x.string)
运行实例
实例
打印匹配的字符串部分
正则表达式查找以大写 “C” 开头的任何单词:
import re str = "China is a great country" x = re.search(r"\bC\w+", str) print(x.group())
运行实例
注释:如果没有匹配项,则返回值 None,而不是 Match 对象。
위 내용은 Python의 RegEx 정규식을 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











많은 웹 사이트 개발자는 램프 아키텍처에서 Node.js 또는 Python 서비스를 통합하는 문제에 직면 해 있습니다. 기존 램프 (Linux Apache MySQL PHP) 아키텍처 웹 사이트 요구 사항 ...

SCAPY 크롤러를 사용할 때 파이프 라인 영구 스토리지 파일을 작성할 수없는 이유는 무엇입니까? 토론 Data Crawler에 Scapy Crawler를 사용하는 법을 배울 때 종종 ...

Python Process Pool은 클라이언트가 갇히게하는 동시 TCP 요청을 처리합니다. 네트워크 프로그래밍에 Python을 사용하는 경우 동시 TCP 요청을 효율적으로 처리하는 것이 중요합니다. ...

functools.partial in Python의 파이썬 funcTools.partial 객체의 시청 방법을 깊이 탐구하십시오 ...

Linux 터미널에서 Python 버전을 보려고 할 때 Linux 터미널에서 Python 버전을 볼 때 권한 문제에 대한 솔루션 ... Python을 입력하십시오 ...

Python 크로스 플랫폼 데스크톱 응용 프로그램 개발 라이브러리 선택 많은 Python 개발자가 Windows 및 Linux 시스템 모두에서 실행할 수있는 데스크탑 응용 프로그램을 개발하고자합니다 ...

Python : 모래 시계 그래픽 도면 및 입력 검증을 시작 하기이 기사는 모래 시계 그래픽 드로잉 프로그램에서 Python 초보자가 발생하는 변수 정의 문제를 해결합니다. 암호...

데이터 변환 및 통계 : 대규모 데이터 세트의 효율적인 처리이 기사는 제품 정보가 포함 된 데이터 목록을 다른 사람으로 변환하는 방법을 자세히 소개합니다 ...
