search
HomeBackend DevelopmentPython TutorialA brief introduction to regular expressions in python (with code)

本篇文章给大家带来的内容是关于python中正则表达式的简单介绍(附代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

正则表达式是对字符串操作的一种逻辑公式,就是用事先定义好的一些特定字符、及这些特定字符的组合,组成一个“规则字符串”,这个“规则字符串”用来表达对字符串的一种过滤逻辑。

在python中正则表达式被封装到了re模块,通过引入re模块来使用正则表达式

re模块中有很正则表达式处理函数,首先用findall函数介绍基本基本字符的含义

元字符有:.  \  *  +  ?  ^  $  |  {}  []  ()

findall函数

遍历匹配,可以获取字符串中所有匹配的字符串,返回一个列表

.  匹配任意除换行符"\n"外的字符

import re

temp=re.findall("a.c","abcdefagch")
print(temp)#['abc', 'agc']

*  匹配前一个字符0或多次

temp=re.findall("a*b","abcaaaaabcdefb")
print(temp)#['ab', 'aaaaab', 'b']

+  匹配前一个字符1次或无限次

temp=re.findall("a+b","abcaaaaabcdefb")
print(temp)#['ab', 'aaaaab']

?  匹配前一个字符0次或1次

temp=re.findall("a?b","abcaaaaabcdefb")
print(temp)#['ab', 'ab', 'b']

^  匹配字符串开头。在多行模式中匹配每一行的开头

temp=re.findall("^ab","abcaaaaabcdefb")
print(temp)#['ab']

$  匹配字符串末尾,在多行模式中匹配每一行的末尾

temp=re.findall("ab$","abcaaaaabcdefab")
print(temp)#['ab']

|  或。匹配|左右表达式任意一个,从左到右匹配,如果|没有包括在()中,则它的范围是整个正则表达式

temp=re.findall("abc|def","abcdef")
print(temp)#['abc', 'def']

{}  {m}匹配前一个字符m次,{m,n}匹配前一个字符m至n次,若省略n,则匹配m至无限次

temp=re.findall("a{3}","aabaaacaaaad")
print(temp)#['aaa', 'aaa']
temp=re.findall("a{3,5}","aaabaaaabaaaaabaaaaaa")
print(temp)#['aaa', 'aaaa', 'aaaaa', 'aaaaa']在获取了3个a后,若下一个还是a,并不会得到aaa,而是算下一个a

[]  字符集。对应的位置可以是字符集中任意字符。字符集中的字符可以逐个列出,也可以给出范围,如[abc]或[a-c]。[^abc]表示取反,即非abc,所有特殊字符在字符集中都失去其原有的特殊含义。用\反斜杠转义恢复特殊字符的特殊含义。

temp=re.findall("a[bcd]e","abcdefagch")
print(temp)#[]此时bcd为b或c或d
temp=re.findall("a[a-z]c","abcdefagch")
print(temp)#['abc', 'agc']
temp=re.findall("[^a]","aaaaabcdefagch")
print(temp)#['b', 'c', 'd', 'e', 'f', 'g', 'c', 'h']
temp=re.findall("[^ab]","aaaaabcdefagch")
print(temp)#['c', 'd', 'e', 'f', 'g', 'c', 'h']a和b都不会被匹配

()  被括起来的表达式将作为分组,从表达式左边开始每遇到一个分组的左括号“(”,编号+1.分组表达式作为一个整体,可以后接数量词。表达式中的|仅在该组中有效。

temp=re.findall("(abc){2}a(123|456)c","abcabca456c")
print(temp)#[('abc', '456')]
temp=re.findall("(abc){2}a(123|456)c","abcabca456cbbabcabca456c")
print(temp)#[('abc', '456'), ('abc', '456')]
#这里有()的情况中,findall会将该规则的每个()中匹配到的字符创放到一个元组中

要想看到被完全匹配的内容,我们可以使用一个新的函数search函数

search函数

在字符串内查找模式匹配,只要找到第一个匹配然后返回,如果字符串没有匹配,则返回None

temp=re.search("(abc){2}a(123|456)c","abcabca456c")
print(temp)#<re.Match object; span=(0, 11), match=&#39;abcabca456c&#39;>
print(temp.group())#abcabca456c

\  转义字符,使后一个字符改变原来的意思

反斜杠后边跟元字符去除特殊功能;(即将特殊字符转义成普通字符)

temp=re.search("a\$","abcabca456ca$")
print(temp)#<<re.Match object; span=(11, 13), match=&#39;a$&#39;>
print(temp.group())#a$

引用序号对应的字组所匹配的字符串。

即下面的\2为前边第二个括号中的内容,2代表第几个,从1开始

a=re.search(r&#39;(abc)(def)gh\2&#39;,&#39;abcdefghabc abcdefghdef&#39;).group()
print(a)#abcdefghdef

反斜杠后边跟普通字符实现特殊功能;(即预定义字符)  

预定义字符有:\d \D \s \S \w \W \A \Z \b \B

预定义字符在字符集中仍有作用

\d  数字:[0-9]

temp=re.search("a\d+b","aaa234bbb")
print(temp.group())#a234b

\D  非数字:[^\d]

\s  匹配任何空白字符:[\t\r\n\f\v]

temp=re.search("a\s+b","aaa   bbb")
print(temp.group())#a   b

\S  非空白字符:[^\s]

\w  匹配包括下划线在内的任何字字符:[A-Za-z0-9_]

\W  匹配非字母字符,即匹配特殊字符

temp=re.search("\W","$")
print(temp.group())#$

\A  仅匹配字符串开头,同^

\Z  仅匹配字符串结尾,同$

\b  匹配\w和\W之间的边界

temp=re.search(r"\bas\b","a as$d")
print(temp.group())#$as

\B  [^\b]

下面介绍其他的re常用函数

compile函数

编译正则表达式模式,返回一个对象的模式

rule = re.compile("abc\d+\w")
str = "aaaabc6def"
temp = rule.findall(str)
print(temp)#[&#39;abc6d&#39;]

match函数

在字符串刚开始的位置匹配,和^功能相同

temp=re.match("asd","asdfasd")
print(temp.group())#asd

 finditer函数

将所有匹配到的字符串以match对象的形式按顺序放到一个迭代器中返回

temp=re.finditer("\d+","as11d22f33a44sd")
print(temp)#<callable_iterator object at 0x00000242EEEE9E48>
for i in temp:
    print(i.group())
#11
#22
#33
#44

split函数

用于分割字符串,将分割后的字符串放到一个列表中返回

如果在字符串的首或尾分割,将会出现一个空字符串

temp=re.split("\d+","as11d22f33a44sd55")
print(temp)#[&#39;as&#39;, &#39;d&#39;, &#39;f&#39;, &#39;a&#39;, &#39;sd&#39;, &#39;&#39;]

使用字符集分割

如下先以a分割,再将分割后的字符串们以b分割,所以会出现3个空字符串

temp=re.split("[ab]","ab123b456ba789b0")
print(temp)#[&#39;&#39;, &#39;&#39;, &#39;123&#39;, &#39;456&#39;, &#39;&#39;, &#39;789&#39;, &#39;0&#39;]

sub函数 

将re匹配到的部分进行替换再返回新的字符串

temp=re.sub("\d+","_","ab123b456ba789b0")
print(temp)#ab_b_ba_b_

后边还可以再加一个参数表示替换次数,默认为0表示全替换

subn函数

将re匹配到的部分进行替换再返回一个装有新字符串和替换次数的元组

temp=re.subn("\d+","_","ab123b456ba789b0")
print(temp)#(&#39;ab_b_ba_b_&#39;, 4)

然后讲一下特殊分组

temp=re.search("(?P<number>\d+)(?P<letter>[a-zA-Z])","ab123b456ba789b0")
print(temp.group("number"))#123
print(temp.group("letter"))#b

以?P的形式起名

 最后说一下惰性匹配和贪婪匹配

temp=re.search("\d+","123456")
print(temp.group())#123456

此时为贪婪匹配,即只要符合就匹配到底

temp=re.search("\d+?","123456")
print(temp.group())#1

在后面加一个?变为惰性匹配,即只要匹配成功一个字符就结束匹配 

 相关推荐:

Python正则表达式介绍

php正则表达式匹配中文字符的简单代码实例

The above is the detailed content of A brief introduction to regular expressions in python (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.