Python 第四章正则表达式(续)
下面举了一些例子:
一,
import re #导入re模块
text = ‘alpha. bata…game der’ #测试用的字符串
re.split(’[. ]+’, text) #使用指定字符作为分隔符进行分隔
[‘alpha’, ‘be\ata’, ‘game’, ‘der’]re.split(’[. ]+’, text, maxsplit=2) #最多分隔2次
[‘alpha’, ‘bata’, ‘game der’]re.split(’[. ]+’, text, maxsplit=1) #最多分隔1次
[‘alpha’, ‘bata…game der’]pat = ‘[a-zA-Z]+’
re.findall(pat, text) #查找所有单词
[‘alpha’, ‘bata’, ‘game’, ‘der’]
二,import re
example = ‘ShanDong Institute of Business and Technology’
pattern = re.compile(r’\bB\w+\b’) #查找以B开头的单词
pattern.findall(example) #使用正则表达式对象的findall()方法
[‘Business’]pattern = re.compile(r’\w+g\b’) #查找以字母g结尾的单词
pattern.findall(example)
[‘ShanDong’]pattern = re.compile(r’\b[a-zA-Z]{3}\b’)#查找3个字母长的单词
pattern.findall(example)
[‘and’]s = ‘ab134ab98723jafjweoruiagab’
m = re.search(r’((ab).){2}.(ab)’, s)#在s中查找ab的第3次出现
m.group(3)
‘ab’m.span(3)
(24, 26)s[24:]
‘ab’