python --正则学习

 

re的正则表达式语法
    正则表达式语法表如下:

 

re.match

  re.match 尝试从字符串的开始匹配一个模式,匹配成功返回match object,否则返回None. 如:下面的例子匹配第一个单词。 

补充说明:

我们可以m.group(number)的方法来查询群。group(0)是整个正则表达的搜索结果,group(1)是第一个群……

import re
m = re.search("output_(d{4})", "output_1986.txt")
print(m.group(1))

我们还可以将群命名,以便更好地使用m.group查询:

import re
m = re.search("output_(?P<year>d{4})", "output_1986.txt")   #(?P<name>...) 为group命名
print(m.group("year"))

 实例1

re.search

  re.search 扫描整个字符串并返回第一个成功的匹配。

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

re.match与re.search的区别:re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。

re.sub

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

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

输出:

JGood-is-a-handsome-boy,-he-is-cool,-clever,-and-so-on...

JGood[ ]is[ ]a[ ]handsome[ ]boy,[ ]he[ ]is[ ]cool,[ ]clever,[ ]and[ ]so[ ]on...

练习

有一个文件,文件名为output_1981.10.21.txt 。下面使用Python: 读取文件名中的日期时间信息,并找出这一天是周几。将文件改名为output_YYYY-MM-DD-W.txt (YYYY:四位的年,MM:两位的月份,DD:两位的日,W:一位的周几,并假设周一为一周第一天)

import os, re, datetime


str1 = "output_1981.10.21.txt"
m = re.search("(d{4}).(d{2}).(d{2})",str1)
d = m.group()
s = re.sub(r'.','-',d)

date = datetime.date(int( m.group(1)),int(m.group(2)),int(m.group(3)))
w2 = date.weekday() + 1
s1=str(w2)

new_str="output_"+s+'_'+s1+".txt"
print new_str

输出:

output_1981-10-21-3.txt

re.split

  可以使用re.split来分割字符串,如:re.split(r's+', text);将字符串按空格分割成一个单词列表。

re.findall

  re.findall可以获取字符串中所有匹配的字符串。如:re.findall(r'w*oow*', text);获取字符串中,包含'oo'的所有单词。

re.compile

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

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

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

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

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

原文地址:https://www.cnblogs.com/saryli/p/5052130.html