Python入门篇之正则表达式
正则表达式有两种基本的操作,分别是匹配和替换。
匹配就是在一个文本字符串中搜索匹配一特殊表达式;
替换就是在一个字符串中查找并替换匹配一特殊表达式的字符串。
1.基本元素
正则表达式定义了一系列的特殊字符元素以执行匹配动作。
正则表达式基本字符
字符 | 描述 |
---|---|
text | 匹配text字符串 |
. | 匹配除换行符之外的任意一个单个字符 |
^ | 匹配一个字符串的开头 |
$ | 匹配一个字符串的末尾 |
在正则表达式中,我们还可用匹配限定符来约束匹配的次数。
匹配限定符
最大匹配 | 最小匹配 | 描述 |
---|---|---|
* | * | 重复匹配前表达式零次或多次 |
+ | + | 重复匹配前表达式一次或多次 |
重复匹配前表达式零次或一次 | ||
{m} | {m} | 精确重复匹配前表达式m次 |
{m,} | {m,} | 至少重复匹配前表达式m次 |
{m,n} | {m,n} | 至少重复匹配前表达式m次,至多重复匹配前表达式n次 |
据上所述,".*"为最大匹配,能匹配源字符串所有能匹配的字符串。".* "为最小匹配,只匹配第一次出现的字符串。如:d.*g能匹配任意以d开头,以g结尾的字符串,如"debug"和"debugging",甚至"dog is walking"。而d.* g只能匹配"debug",在"dog is walking"字符串中,则只匹配到"dog "。
在一些更复杂的匹配中,我们可用到组和运算符。
组和运算符
组 | 描述 |
---|---|
[...] | 匹配集合内的字符,如[a-z],[1-9]或[,./;'] |
[^...] | 匹配除集合外的所有字符,相当于取反操作 |
A|B | 匹配表达式A或B,相当于OR操作 |
(...) | 表达式分组,每对括号为一组,如([a-b]+)([A-Z]+)([1-9]+) |
\number | 匹配在number表达式组内的文本 |
有一组特殊的字符序列,用来匹配具体的字符类型或字符环境。如\b匹配字符边界,food\b匹配"food"、"zoofood",而和"foodies"不匹配。
特殊字符序列
字符 | 描述 |
---|---|
\A | 只匹配字符串的开始 |
\b | 匹配一个单词边界 |
\B | 匹配一个单词的非边界 |
\d | 匹配任意十进制数字字符,等价于r'[0-9]' |
\D | 匹配任意非十进制数字字符,等价于r'[^0-9]' |
\s | 匹配任意空格字符(空格符、tab制表符、换行符、回车、换页符、垂直线符号) |
\S | 匹配任意非空格字符 |
\w | 匹配任意字母数字字符 |
\W | 匹配任意非字母数字字符 |
\Z | 仅匹配字符串的尾部 |
\\ | 匹配反斜线字符 |
有一套声明(assertion)对具体事件进行声明。
正则表达式声明
声明 | 描述 |
---|---|
( iLmsux) | 匹配空字符串,iLmsux字符对应下表的正则表达式修饰符。 |
( :...) | 匹配圆括号内定义的表达式,但不填充字符组表。 |
( P |
匹配圆括号内定义的表达式,但匹配的表达式还可用作name标识的符号组。 |
( P=name) | 匹配所有与前面命名的字符组相匹配的文本。 |
( #...) | 引入注释,忽略圆括号内的内容。 |
( =...) | 如果所提供的文本与下一个正则表达式元素匹配,这之间没有多余的文本就匹配。这允许在一个表达式中进行超前操作,而不影响正则表达式其余部分的分析。如"Martin"其后紧跟"Brown",则"Martin( =Brown)"就只与"Martin"匹配。 |
( !...) | 仅当指定表达式与下一个正则表达式元素不匹配时匹配,是( =...)的反操作。 |
( | 如果字符串当前位置的前缀字符串是给定文本,就匹配,整个表达式就在当前位置终止。如( |
( | 如果字符串当前位置的前缀字符串不是给定的正文,就匹配,是( |
正则表达式还支持一些处理标志,它会影响正则式的执行方法。
处理标志
标志 | 描述 |
---|---|
I或IGNORECASE | 忽略表达式的大小写来匹配文本。 |
2.操作
通过re模块,我们就可在python中利用正则式对字符串进行搜索、抽取和替换操作。如:re.search()函数能执行一个基本的搜索操作,它能返回一个MatchObject对象。re.findall()函数能返回匹配列表。
代码如下:
>>> import re
>>> a="this is my re module test"
>>> obj = re.search(r'.*is',a)
>>> print obj
<_sre.sre_match object at>
>>> obj.group()
'this is'
>>> re.findall(r'.*is',a)
['this is']
MatchObject对象方法
方法 | 描述 |
---|---|
expand(template) | 展开模板中用反斜线定义的内容。 |
m.group([group,...]) | 返回匹配的文本,是个元组。此文本是与给定group或由其索引数字定义的组匹配的文本,如果没有组定组名,则返回所有匹配项。 |
m.groups([default]) | 返回一个元组,该元组包含模式中与所有组匹配的文本。如果给出default参数,default参数值就是与给定表达式不匹配的组的返回值。default参数的默认取值为None。 |
m.groupdict([default]) | 返回一个字典,该字典包含匹配的所有子组。如果给出default参数,其值就是那些不匹配组的返回值。default参数的默认取值为None。 |
m.start([group]) | 返回指定group的开始位置,或返回全部匹配的开始位置。 |
m.end([group]) | 返回指定group的结束位置,或返回全部匹配的结束位置。 |
m.span([group]) | 返回两元素组,此元组等价于关于一给定组或一个完整匹配表达式的(m.start(group),m.end(group)))列表 |
m.pos | 传递给match()或search()函数的pos值。 |
m.endpos | 传递给match()或search()函数的endpos值。 |
m.lastindex | |
m.lastgroup | |
m.re | 创建这个MatchObject对象的正则式对象 |
m.string | 提供给match()或search()函数的字符串。 |
使用sub()或subn()函数可在字符串上执行替换操作。sub()函数的基本格式如下:
sub(pattern,replace,string[,count])
示例
代码如下:
>>> str = 'The dog on my bed'
>>> rep = re.sub('dog','cat',str)
>>> print rep
The cat on my bed
replace参数可接受函数。要获得替换的次数,可使用subn()函数。subn()函数返回一个元组,此元组包含替换了的文本和替换的次数。
如果需用同一个正则式进行多次匹配操作,我们可把正则式编译成内部语言,提高处理速度。编译正则式用compile()函数来实现。compile()函数的基本格式如下:
compile(str[,flags])
str表示需编译的正则式串,flags是修饰标志符。正则式被编译后生成一个对象,该对象有多种方法和属性。
正则式对象方法/属性
方法/属性 | 描述 |
---|---|
r.search(string[,pos[,endpos]]) | 同search()函数,但此函数允许指定搜索的起点和终点 |
r.match(string[,pos[,endpos]]) | 同match()函数,但此函数允许指定搜索的起点和终点 |
r.split(string[,max]) | 同split()函数 |
r.findall(string) | 同findall()函数 |
r.sub(replace,string[,count]) | 同sub()函数 |
r.subn(replace,string[,count]) | 同subn()函数 |
r.flags | 创建对象时定义的标志 |
r.groupindex | 将r'( Pid)'定义的符号组名字映射为组序号的字典 |
r.pattern | 在创建对象时使用的模式 |
转义字符串用re.escape()函数。
通过getattr获取对象引用
代码如下:
>>> li=['a','b']
>>> getattr(li,'append')
>>> getattr(li,'append')('c') #相当于li.append('c')
>>> li
['a', 'b', 'c']
>>> handler=getattr(li,'append',None)
>>> handler
>>> handler('cc') #相当于li.append('cc')
>>> li
['a','b','c','cc']
>>>result = handler('bb')
>>>li
['a','b','c','cc','bb']
>>>print result
None

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.

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.

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.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

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".

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
