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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Python은 배우고 사용하기 쉽고 C는 더 강력하지만 복잡합니다. 1. Python Syntax는 간결하며 초보자에게 적합합니다. 동적 타이핑 및 자동 메모리 관리를 사용하면 사용하기 쉽지만 런타임 오류가 발생할 수 있습니다. 2.C는 고성능 응용 프로그램에 적합한 저수준 제어 및 고급 기능을 제공하지만 학습 임계 값이 높고 수동 메모리 및 유형 안전 관리가 필요합니다.

Python과 C는 메모리 관리 및 제어에 상당한 차이가 있습니다. 1. Python은 참조 계산 및 쓰레기 수집을 기반으로 자동 메모리 관리를 사용하여 프로그래머의 작업을 단순화합니다. 2.C는 메모리 수동 관리가 필요하므로 더 많은 제어를 제공하지만 복잡성과 오류 위험을 증가시킵니다. 선택할 언어는 프로젝트 요구 사항 및 팀 기술 스택을 기반으로해야합니다.

과학 컴퓨팅에서 Python의 응용 프로그램에는 데이터 분석, 머신 러닝, 수치 시뮬레이션 및 시각화가 포함됩니다. 1.numpy는 효율적인 다차원 배열 및 수학적 함수를 제공합니다. 2. Scipy는 Numpy 기능을 확장하고 최적화 및 선형 대수 도구를 제공합니다. 3. 팬더는 데이터 처리 및 분석에 사용됩니다. 4. matplotlib는 다양한 그래프와 시각적 결과를 생성하는 데 사용됩니다.

Python 또는 C를 선택할 것인지 프로젝트 요구 사항에 따라 다릅니다. 1) Python은 간결한 구문 및 풍부한 라이브러리로 인해 빠른 개발, 데이터 과학 및 스크립팅에 적합합니다. 2) C는 컴파일 및 수동 메모리 관리로 인해 시스템 프로그래밍 및 게임 개발과 같은 고성능 및 기본 제어가 필요한 시나리오에 적합합니다.

Python은 데이터 과학 및 기계 학습에 널리 사용되며 주로 단순성과 강력한 라이브러리 생태계에 의존합니다. 1) 팬더는 데이터 처리 및 분석에 사용되며, 2) Numpy는 효율적인 수치 계산을 제공하며 3) Scikit-Learn은 기계 학습 모델 구성 및 최적화에 사용되며 이러한 라이브러리는 Python을 데이터 과학 및 기계 학습에 이상적인 도구로 만듭니다.

하루에 2 시간 동안 파이썬을 배우는 것으로 충분합니까? 목표와 학습 방법에 따라 다릅니다. 1) 명확한 학습 계획을 개발, 2) 적절한 학습 자원 및 방법을 선택하고 3) 실습 연습 및 검토 및 통합 연습 및 검토 및 통합,이 기간 동안 Python의 기본 지식과 고급 기능을 점차적으로 마스터 할 수 있습니다.

웹 개발에서 Python의 주요 응용 프로그램에는 Django 및 Flask 프레임 워크 사용, API 개발, 데이터 분석 및 시각화, 머신 러닝 및 AI 및 성능 최적화가 포함됩니다. 1. Django 및 Flask 프레임 워크 : Django는 복잡한 응용 분야의 빠른 개발에 적합하며 플라스크는 소형 또는 고도로 맞춤형 프로젝트에 적합합니다. 2. API 개발 : Flask 또는 DjangorestFramework를 사용하여 RESTFULAPI를 구축하십시오. 3. 데이터 분석 및 시각화 : Python을 사용하여 데이터를 처리하고 웹 인터페이스를 통해 표시합니다. 4. 머신 러닝 및 AI : 파이썬은 지능형 웹 애플리케이션을 구축하는 데 사용됩니다. 5. 성능 최적화 : 비동기 프로그래밍, 캐싱 및 코드를 통해 최적화

Python은 개발 효율에서 C보다 낫지 만 C는 실행 성능이 높습니다. 1. Python의 간결한 구문 및 풍부한 라이브러리는 개발 효율성을 향상시킵니다. 2.C의 컴파일 유형 특성 및 하드웨어 제어는 실행 성능을 향상시킵니다. 선택할 때는 프로젝트 요구에 따라 개발 속도 및 실행 효율성을 평가해야합니다.


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

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

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

PhpStorm 맥 버전
최신(2018.2.1) 전문 PHP 통합 개발 도구
