python re模块学习--正则表达式函数

简介:

    这里主要介绍Python中常用的正则表达式处理函数。关于python中正则表达式的语法会再总结一篇博文。

re.match

re.match 尝试从字符串的开始匹配一个模式,如:下面的例子匹配第一个单词。

代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
m = re.match(r"(\w+)\s", text)
if m:
    print m.group(0), '\n', m.group(1)
else:
    print 'not match'

执行结果如下:

[root@90-99 oldboy]# python a.py 
JGood  
JGood

如果 text = "#JGood is a handsome boy, he is cool, clever, and so on..."  则执行结果如下:

[root@90-99 oldboy]# python a.py 
not match

#me:补充

group和groups是两个不同的函数

一般,m.group(N)返回第N组括号匹配的字符

而m.group()==m.group(0)==所有匹配的字符,与括号无关

m.groups()返回所有括号匹配的字符,以tuple的格式

m.groups()==(m.group(0),m.group(1),...)


re.match的函数原型为:re.match(pattern, string, flags)

第一个参数是正则表达式(需要你指定对应的r前缀),这里为"(\w+)\s",如果匹配成功,则返回一个Match,否则返回一个None;

第二个参数表示要匹配的字符串;

第三个参数是标致位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。 


re.search

re.search函数会在整个字符串内查找模式匹配,只到找到第一个匹配然后返回,如果字符串没有匹配,则返回None。

代码如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re

text = "JGood is a handsome boy, he is cool, clever, and so on..."
m = re.search(r'\shan(ds)ome\s', text)
if m:
    print m.group(0), m.group(1)
else:
    print 'not search'

执行结果如下:

[root@90-99 oldboy]# python b.py 
 handsome  ds

re.search的函数原型为: re.search(pattern, string, flags)

每个参数的含意与re.match一样。 

re.match与re.search的区别:

match :只从字符串的开始与正则表达式匹配,匹配成功返回matchobject,否则返回none;

search :将字符串的所有字串尝试与正则表达式匹配,如果所有的字串都没有匹配成功,返回none,否则返回matchobject;


re.sub

re.sub用于替换字符串中的匹配项。下面一个例子将字符串中的空格 ' ' 替换成 '-' :  

代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re

text = "JGood is a handsome boy, he is cool, clever, and so on..."
print re.sub(r'\s+', '-', text)

执行结果如下:

[root@90-99 oldboy]# python a.py 
JGood-is-a-handsome-boy,-he-is-cool,-clever,-and-so-on...

re.sub的函数原型为:re.sub(pattern, repl, string, count)

其中第一个参数是要匹配的正则表达式;

第二个参数是替换后的字符串;本例中为'-'

第四个参数指替换个数。默认为0,表示每个匹配项都替换。

re.sub还允许使用函数对匹配项的替换进行复杂的处理。如:re.sub(r'\s', lambda m: '[' + m.group(0) + ']', text, 0);将字符串中的空格' '替换为'[ ]'。

代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re

text = "JGood is a handsome boy, he is cool, clever, and so on..."
print re.sub(r'\s', lambda m: '[' + m.group(0) + ']', text, 0);

执行结果如下:

[root@90-99 oldboy]# python a.py 
JGood[ ]is[ ]a[ ]handsome[ ]boy,[ ]he[ ]is[ ]cool,[ ]clever,[ ]and[ ]so[ ]on...

补充:re.sub 的pattern中支持反斜杠加数字(\N)这样的参数(类似于sed中的 \1 这样的功能)

示例代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
inputStr = "hello crifan, nihao crifan";
replacedStr = re.sub(r"hello (\w+), nihao \1", "crifanli", inputStr);
print "replacedStr=",replacedStr; 

执行结果如下:

[root@90-99 oldboy]# python a.py 
replacedStr= crifanli


re.subn

与re.sub方法作用一样,但返回的是包含新字符串和替换执行次数的两元组。

代码示例如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re

text = "JGood is a handsome boy, he is cool, clever, and so on..."
print re.subn(r'\s+', '-', text)

执行结果如下:

[root@90-99 oldboy]# python a.py 
('JGood-is-a-handsome-boy,-he-is-cool,-clever,-and-so-on...', 11)


re.split

  可以使用re.split利用指定的字符(或者指定正则表达式匹配的字符)来分割字符串(text),如:re.split(r'\s+', text);将字符串按空格分割成一个单词-----返回值是一个列表类型。

代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re

text = "JGood is a handsome boy, he is cool, clever, and so on..."
print re.split(r'\s+', text);

执行结果如下:

[root@90-99 oldboy]# python a.py 
['JGood', 'is', 'a', 'handsome', 'boy,', 'he', 'is', 'cool,', 'clever,', 'and', 'so', 'on...']

#me:补充

re.split(pattern,string.maxsplit=0)
maxsplit是分离的次数,maxsplit=1分离一次,默认为0,不限制次数。

通过正则表达式将字符串分离。如果用括号将正则表达式括起来,那么匹配的字符串也会被列入到list中返回。

>>> re.split('\W+', 'Words, words, words.') 
['Words', 'words', 'words', ''] 
>>> re.split('(\W+)', 'Words, words, words.') 
['Words', ', ', 'words', ', ', 'words', '.', ''] 
>>> re.split('\W+', 'Words, words, words.', 1) 
['Words', 'words, words.']


re.findall

re.findall可以获取字符串(text)中所有与正则表达式匹配的字符串。如:re.findall(r'\w*oo\w*', text);获取字符串中,包含'oo'的所有单词。-----返回值是一个列表类型。

代码示例如下;

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re

text = "JGood is a handsome boy, he is cool, clever, and so on..."
print re.findall(r'\w*oo\w*', text);

执行结果如下:

[root@90-99 oldboy]# python a.py 
['JGood', 'cool']


re.finditer

找到 RE 匹配的所有子串,并把它们作为一个迭代器(iterator)返回。这个匹配是从左到右有序地返回。如果无匹配,返回空列表。

代码示例如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
it = re.finditer(r"\d+","12a32bc43jf3") 
for match in it:
    print match.group()

执行结果如下:

[root@90-99 oldboy]# python a.py 
12
32
43
3


re.compile

  可以把正则表达式编译成一个正则表达式对象。可以把那些经常使用的正则表达式编译成正则表达式对象,这样可以提高一定的效率。下面是一个正则表达式对象的一个例子:

代码示例如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re

text = "JGood is a handsome boy, he is cool, clever, and so on..."
regex = re.compile(r'\w*oo\w*')
print regex.findall(text)   #查找所有包含'oo'的单词
print regex.sub(lambda m: '[' + m.group(0) + ']', text) #将字符串中含有'oo'的单词用[]括起来。

执行结果如下:

[root@90-99 oldboy]# python a.py 
['JGood', 'cool']
[JGood] is a handsome boy, he is [cool], clever, and so on...



      本文转自Tenderrain 51CTO博客,原文链接:http://blog.51cto.com/tenderrain/1613754,如需转载请自行联系原作者






相关文章
|
1天前
|
数据挖掘 数据处理 索引
python常用pandas函数nlargest / nsmallest及其手动实现
python常用pandas函数nlargest / nsmallest及其手动实现
9 0
|
1天前
|
开发者 Python
Python的os模块详解
Python的os模块详解
9 0
|
4天前
|
数据挖掘 API 数据安全/隐私保护
python请求模块requests如何添加代理ip
python请求模块requests如何添加代理ip
|
6天前
|
测试技术 Python
Python 有趣的模块之pynupt——通过pynput控制鼠标和键盘
Python 有趣的模块之pynupt——通过pynput控制鼠标和键盘
|
6天前
|
Serverless 开发者 Python
《Python 简易速速上手小册》第3章:Python 的函数和模块(2024 最新版)
《Python 简易速速上手小册》第3章:Python 的函数和模块(2024 最新版)
38 1
|
6天前
|
索引 Python
Python高维变量选择:SCAD平滑剪切绝对偏差惩罚、Lasso惩罚函数比较
Python高维变量选择:SCAD平滑剪切绝对偏差惩罚、Lasso惩罚函数比较
|
7天前
|
机器学习/深度学习 算法 Python
使用Python实现集成学习算法:Bagging与Boosting
使用Python实现集成学习算法:Bagging与Boosting
18 0
|
8天前
|
Python
python学习-函数模块,数据结构,字符串和列表(下)
python学习-函数模块,数据结构,字符串和列表
49 0
|
8天前
05-python之函数-函数的定义/函数的参数/函数返回值/函数说明文档/函数的嵌套使用/函数变量的作用域
05-python之函数-函数的定义/函数的参数/函数返回值/函数说明文档/函数的嵌套使用/函数变量的作用域
|
9天前
|
Python
python学习14-模块与包
python学习14-模块与包