목차
RegEx 모듈
RegEx in Python
RegEx 함수
메타 문자
특수 시퀀스
集合(Set)
findall() 函数
search() 函数
split() 函数
sub() 函数
Match 对象
백엔드 개발 파이썬 튜토리얼 Python의 RegEx 정규식을 사용하는 방법

Python의 RegEx 정규식을 사용하는 방법

May 19, 2023 pm 08:49 PM
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")
로그인 후 복사

Python의 RegEx 정규식을 사용하는 방법

RegEx 함수

re 모듈은 일치를 위해 문자열을 검색할 수 있는 함수 세트를 제공합니다.

Python의 RegEx 정규식을 사용하는 방법

메타 문자

메타 문자는 다음과 같습니다.

문자: [] 설명: 문자 예 세트: "[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)
로그인 후 복사

예제 실행

Python의 RegEx 정규식을 사용하는 방법

문자: 설명: 특수 시퀀스를 나타냅니다(이스케이프에도 사용할 수 있음) 특수 문자) 예: "d"

import re

str = "That will be 59 dollars"

#Find all digit characters:

x = re.findall("\d", str)
print(x)
로그인 후 복사

Run 예

Python의 RegEx 정규식을 사용하는 방법

문자: . 설명: 모든 문자(줄 바꿈 제외) 예: "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 예

Python의 RegEx 정규식을 사용하는 방법

문자: ^ 설명 : 시작 예: "^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

Python의 RegEx 정규식을 사용하는 방법

문자: $ 설명: 끝 예: "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

Python의 RegEx 정규식을 사용하는 방법

문자: * 설명: 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")
로그인 후 복사

예제 실행

Python의 RegEx 정규식을 사용하는 방법

문자: + 설명: 하나 이상의 발생 예: "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")
로그인 후 복사

예제 실행

Python의 RegEx 정규식을 사용하는 방법

문자: {} 설명 : 발생 횟수를 정확하게 지정 예: "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")
로그인 후 복사

예제 실행

Python의 RegEx 정규식을 사용하는 방법

문자: | 설명: 둘 중 하나 예: "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")
로그인 후 복사

예제 실행

Python의 RegEx 정규식을 사용하는 방법

문자 : ( ) 설명 : 캡처 및 그룹화

특수 시퀀스

특수 시퀀스는 아래 표의 문자 중 하나가 뒤에 오는 문자를 말하며 특별한 의미를 갖습니다.

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")
로그인 후 복사

예제 실행

Python의 RegEx 정규식을 사용하는 방법

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")
로그인 후 복사

예제 실행

Python의 RegEx 정규식을 사용하는 방법

예: 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")
로그인 후 복사

예제 실행

Python의 RegEx 정규식을 사용하는 방법

문자 : 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")
로그인 후 복사

예제 실행

Python의 RegEx 정규식을 사용하는 방법

예: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")
로그인 후 복사

예제 실행

Python의 RegEx 정규식을 사용하는 방법

문자: 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")
로그인 후 복사

예제 실행

Python의 RegEx 정규식을 사용하는 방법

문자: 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")
로그인 후 복사

예제 실행

Python의 RegEx 정규식을 사용하는 방법

문자: 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")
로그인 후 복사

运行示例

Python의 RegEx 정규식을 사용하는 방법

字符:\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")
로그인 후 복사

运行示例

Python의 RegEx 정규식을 사용하는 방법

字符:\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")
로그인 후 복사

运行示例

Python의 RegEx 정규식을 사용하는 방법

字符:\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")
로그인 후 복사

运行示例

Python의 RegEx 정규식을 사용하는 방법

字符:\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")
로그인 후 복사

运行示例

Python의 RegEx 정규식을 사용하는 방법

集合(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")
로그인 후 복사

运行示例

Python의 RegEx 정규식을 사용하는 방법

字符:[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")
로그인 후 복사

运行示例

Python의 RegEx 정규식을 사용하는 방법

字符:[^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")
로그인 후 복사

运行示例

Python의 RegEx 정규식을 사용하는 방법

字符:[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")
로그인 후 복사

运行示例

Python의 RegEx 정규식을 사용하는 방법

字符:[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")
로그인 후 복사

运行示例

Python의 RegEx 정규식을 사용하는 방법

字符:[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")
로그인 후 복사

运行示例

Python의 RegEx 정규식을 사용하는 방법

字符:[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")
로그인 후 복사

运行示例

Python의 RegEx 정규식을 사용하는 방법

字符:[+]

描述:在集合中,+、*、.、|、()、$、{} 没有特殊含义,因此 [+] 表示:返回字符串中任何 + 字符的匹配项。

示例

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")
로그인 후 복사

运行示例

Python의 RegEx 정규식을 사용하는 방법

findall() 函数

findall() 函数返回包含所有匹配项的列表。

实例

打印所有匹配的列表

import re

str = "China is a great country"
x = re.findall("a", str)
print(x)
로그인 후 복사

运行实例

Python의 RegEx 정규식을 사용하는 방법

这个列表以被找到的顺序包含匹配项。

如果未找到匹配项,则返回空列表。

实例

如果未找到匹配,则返回空列表:

import re

str = "China is a great country"
x = re.findall("USA", str)
print(x)
로그인 후 복사

运行实例

Python의 RegEx 정규식을 사용하는 방법

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())
로그인 후 복사

运行实例

Python의 RegEx 정규식을 사용하는 방법

如果未找到匹配,则返回值 None:

实例

进行不返回匹配的检索

import re

str = "China is a great country"
x = re.search("USA", str)
print(x)
로그인 후 복사

运行实例

Python의 RegEx 정규식을 사용하는 방법

split() 函数

split() 函数返回一个列表,其中字符串在每次匹配时被拆分。

实例

在每个空白字符处进行拆分

import re

str = "China is a great country"
x = re.split("\s", str)
print(x)
로그인 후 복사

运行实例

Python의 RegEx 정규식을 사용하는 방법

可以通过指定 maxsplit 参数来控制出现次数:

实例

仅在首次出现时拆分字符串:

import re

str = "China is a great country"
x = re.split("\s", str, 1)
print(x)
로그인 후 복사

运行实例

Python의 RegEx 정규식을 사용하는 방법

sub() 函数

sub() 函数把匹配替换为您选择的文本

实例

用数字 9 替换每个空白字符

import re

str = "China is a great country"
x = re.sub("\s", "9", str)
print(x)
로그인 후 복사

运行实例

Python의 RegEx 정규식을 사용하는 방법

可以通过指定 count 参数来控制替换次数:

实例

替换前两次出现

import re

str = "China is a great country"
x = re.sub("\s", "9", str, 2)
print(x)
로그인 후 복사

运行实例

Python의 RegEx 정규식을 사용하는 방법

Match 对象

Match 对象是包含有关搜索和结果信息的对象。

注释:如果没有匹配,则返回值 None,而不是 Match 对象。

实例

执行会返回 Match 对象的搜索:

import re

str = "China is a great country"
x = re.search("a", str)
print(x) # 将打印一个对象
로그인 후 복사

运行实例

Python의 RegEx 정규식을 사용하는 방법

Match 对象提供了用于取回有关搜索及结果信息的属性和方法:

  • span() 返回的元组包含了匹配的开始和结束位置

  • .string 返回传入函数的字符串

  • group() 返回匹配的字符串部分

实例

打印首个匹配出现的位置(开始和结束位置)。

正则表达式查找以大写 “C” 开头的任何单词:

import re

str = "China is a great country"
x = re.search(r"\bC\w+", str)
print(x.span())
로그인 후 복사

运行实例

Python의 RegEx 정규식을 사용하는 방법

实例

打印传入函数的字符串

import re

str = "China is a great country"
x = re.search(r"\bC\w+", str)
print(x.string)
로그인 후 복사

运行实例

Python의 RegEx 정규식을 사용하는 방법

实例

打印匹配的字符串部分

正则表达式查找以大写 “C” 开头的任何单词:

import re

str = "China is a great country"
x = re.search(r"\bC\w+", str)
print(x.group())
로그인 후 복사

运行实例

Python의 RegEx 정규식을 사용하는 방법

注释:如果没有匹配项,则返回值 None,而不是 Match 对象。

위 내용은 Python의 RegEx 정규식을 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

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

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

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

램프 아키텍처에서 Node.js 또는 Python 서비스를 효율적으로 통합하는 방법은 무엇입니까? 램프 아키텍처에서 Node.js 또는 Python 서비스를 효율적으로 통합하는 방법은 무엇입니까? Apr 01, 2025 pm 02:48 PM

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

SCAPY 크롤러를 사용할 때 파이프 라인 영구 스토리지 파일을 작성할 수없는 이유는 무엇입니까? SCAPY 크롤러를 사용할 때 파이프 라인 영구 스토리지 파일을 작성할 수없는 이유는 무엇입니까? Apr 01, 2025 pm 04:03 PM

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

Python Process Pool이 동시 TCP 요청을 처리하고 클라이언트가 막히게하는 이유는 무엇입니까? Python Process Pool이 동시 TCP 요청을 처리하고 클라이언트가 막히게하는 이유는 무엇입니까? Apr 01, 2025 pm 04:09 PM

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

Python functools.partial 객체가 내부적으로 캡슐화 한 원래 함수를 보는 방법? Python functools.partial 객체가 내부적으로 캡슐화 한 원래 함수를 보는 방법? Apr 01, 2025 pm 04:15 PM

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

Linux 터미널에서 Python 버전을 볼 때 발생하는 권한 문제를 해결하는 방법은 무엇입니까? Linux 터미널에서 Python 버전을 볼 때 발생하는 권한 문제를 해결하는 방법은 무엇입니까? Apr 01, 2025 pm 05:09 PM

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

Python Cross-Platform 데스크탑 응용 프로그램 개발 : 어떤 GUI 라이브러리가 가장 적합합니까? Python Cross-Platform 데스크탑 응용 프로그램 개발 : 어떤 GUI 라이브러리가 가장 적합합니까? Apr 01, 2025 pm 05:24 PM

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

파이썬 모래시 그래프 그리기 : 가변적 인 정의되지 않은 오류를 피하는 방법? 파이썬 모래시 그래프 그리기 : 가변적 인 정의되지 않은 오류를 피하는 방법? Apr 01, 2025 pm 06:27 PM

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

파이썬에서 대형 제품 데이터 세트를 효율적으로 계산하고 정렬하는 방법은 무엇입니까? 파이썬에서 대형 제품 데이터 세트를 효율적으로 계산하고 정렬하는 방법은 무엇입니까? Apr 01, 2025 pm 08:03 PM

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

See all articles