


A 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='abcabca456c'> print(temp.group())#abcabca456c
\ 转义字符,使后一个字符改变原来的意思
反斜杠后边跟元字符去除特殊功能;(即将特殊字符转义成普通字符)
temp=re.search("a\$","abcabca456ca$") print(temp)#<<re.Match object; span=(11, 13), match='a$'> print(temp.group())#a$
引用序号对应的字组所匹配的字符串。
即下面的\2为前边第二个括号中的内容,2代表第几个,从1开始
a=re.search(r'(abc)(def)gh\2','abcdefghabc abcdefghdef').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)#['abc6d']
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)#['as', 'd', 'f', 'a', 'sd', '']
使用字符集分割
如下先以a分割,再将分割后的字符串们以b分割,所以会出现3个空字符串
temp=re.split("[ab]","ab123b456ba789b0") print(temp)#['', '', '123', '456', '', '789', '0']
sub函数
将re匹配到的部分进行替换再返回新的字符串
temp=re.sub("\d+","_","ab123b456ba789b0") print(temp)#ab_b_ba_b_
后边还可以再加一个参数表示替换次数,默认为0表示全替换
subn函数
将re匹配到的部分进行替换再返回一个装有新字符串和替换次数的元组
temp=re.subn("\d+","_","ab123b456ba789b0") print(temp)#('ab_b_ba_b_', 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
在后面加一个?变为惰性匹配,即只要匹配成功一个字符就结束匹配
相关推荐:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
