Python 正则表达式 Howto(8)

修改字符串

到目前为止,我们只是在特定串中搜索模式。正则表达式也可以使用下列方法来修改字符串:

Method/Attribute

Purpose

split()

Split the string into a list, splitting it wherever the RE matches

sub()

Find all substrings where the RE matches, and replace them with a different string

subn()

Does the same thing as sub(), but returns the new string and the number of replacements

分割串

split() 方法可以再RE匹配的地方讲一个串分割,并且返回一个列表。它很像字符串函数split()只是他可以使用更加广泛的分隔符。像你期望的那样,也有一个模块级的函数 re.split() 。

.split(string[, maxsplit=0])

通过正则匹配来分割字符串。如果在RE中使用了捕捉括号(组),他们的内容会作为一个列表返回。你可以通过传入一个maxsplit 参数来限制分割快的数量。如果maxsplit  非0,至多有maxsplit  个分隔被处理。剩下的会作为最后列表中的最后一个元素。在下列例子中,分隔符是任何的非字母数字字符

>>> 

>>> p= re.compile(r'\W+')
>>> p.split('This is a test, short and sweet, of split().')
['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', '']
>>> p.split('This is a test, short and sweet, of split().',3)
['This', 'is', 'a', 'test, short and sweet, of split().']

有时你可能不仅仅对分隔符之间的匹配感兴趣,对于分隔符(实际上是用作分割的内容)也同样感兴趣。如果使用了捕捉括号,他们的值也会返回

>>> 

>>> p= re.compile(r'\W+')
>>> p2= re.compile(r'(\W+)')
>>> p.split('This... is a test.')
['This', 'is', 'a', 'test', '']
>>> p2.split('This... is a test.')
['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']

模块级别的函数 re.split() 除了将RE作为第一个参数, 其他的都一样

>>> 

>>> 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.']

查询并替换

另外一个常见的任务就是找到所有的匹配,然后替换成其他的字符串。sub() 函数的参数有替换值, 可以是一个字符串或者一个处理字符串的函数.

.sub(replacementstring[, count=0])

返回一个字符串,这个串是从最左边开始,所有模式出现的位置都被替换成了替换值。如果模式没有发现,字符串不会被改变。可选的参数count  是模式替换的最大值,必须是一个非负值,默认值0指的是替换所有的匹配的模式。

下面是使用sub() 函数的例子,他会替换所有的colour 成colour:

>>> 

>>> p= re.compile('(blue|white|red)')
>>> p.sub('colour','blue socks and red shoes')
'colour socks and colour shoes'
>>> p.sub('colour','blue socks and red shoes', count=1)
'colour socks and red shoes'

subn() 左右基本上跟sub()相同, 但是会返回一个有两个元素的元组,一个是替换后的字符串,一个就是替换了多少次:

>>> 

>>> p= re.compile('(blue|white|red)')
>>> p.subn('colour','blue socks and red shoes')
('colour socks and colour shoes', 2)
>>> p.subn('colour','no colours at all')
('no colours at all', 0)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值