2020-1-2(86)

1、匹配一行文字中的所有开头的字母内容

import re
s="abcABC123&*abc"
result=re.match(r"[a-z]+",s,re.I).group()
print(result)

2、匹配一行文字中的所有开头的数字内容

s="123abcABC&*abc123"
result=re.match(r"[0-9]+",s).group()
print(result)

3、匹配一行文字中的所有开头的数字内容或数字内容

s="123abcABC&*abc123"
result=re.match(r"[a-z0-9]+",s,re.I).group()
print(result)

4、 只匹配包含字母和数字的行

with open("d:\\2019\\1.txt") as fp:
    for line in fp:
        if re.match(r"[a-zA-Z0-9]+$",line.strip()):
            print(line)

5、写一个正则表达式,使其能同时识别下面所有的字符串: ‘bat’, ‘bit’, ‘but’, ‘hat’, ‘hit’, ‘hut’

l=['bat', 'bit', 'but', 'hat', 'hit', 'hut']
for i in l:
    if re.match(r"[b|h][a|i|u]t",i) is None:
        print("匹配失败")
else:
    print("全部匹配成功")

6、匹配所有合法的python标识符

var_list = ["Abc112_","akkk_222A","_12ABc","123abcA"]
for i in var_list:
    if re.match(r"[a-zA-Z_]\w+",i):
        print(i+"合法")
    else:
        print(i+"不合法")

7、提取每行中完整的年月日和时间字段

with open("d:\\2019\\1.txt") as fp:
    for line in fp:
        if re.match(r"\d{4}-[0|1][0-9]-[0-3][0-9]\s[0-2][0-4]:[0-5][0-9]:[0-5][0-9]",line.strip()):
            print(line)

8、将每行中的电子邮件地址替换为你自己的电子邮件地址

content_list=[]
with open("d:\\2019\\1.txt") as fp:
    for line in fp:
        print(line)
with open("d:\\2019\\1.txt") as fp:
    for line in fp:
        new_content=re.sub(r"\w+@\w+\.com","1005571161@qq.com",line.strip())+"\n"
        content_list.append(new_content)
with open("d:\\2019\\1.txt","w") as fp:
    fp.writelines(content_list)
with open("d:\\2019\\1.txt") as fp:    
    print(fp.read())

9、匹配\home关键字:

print(re.match(r"\\home","\home").group())

10、使用正则提取出字符串中的单词

s="I am a boy"
result=re.findall(r"\b\w+\b",s)
print(result)
result=re.split(r"\s",s)
print(result)

11.14 pattern.sub

pattern.sub(repl,string,count) repl替换string中匹配的子串 count默认为0
(1)repl为字符串

>>> s="i say, helllo word"
>>> re.findall(r"(\w+) (\w+)",s)
[('i', 'say'), ('helllo', 'word')]
>>> p=re.compile(r"(\w+) (\w+)")
>>> p.sub(r"\2 \1",s)  #\2, \1表示分组引用,分别代表第二个分组,第一个分组
'say i, word helllo'

>>> p=re.compile(r"(?P<g1>\w+) (?P<g2>\w+)")  #第一个分组名为g1,第二个分组名为g2
>>> p.sub(r"\g<g2>,\g<g1>",s)
'say,i,world,hello'

(2)repl为函数
pattern.sub(func,string,count)
必须传一个Match对象,并且必须返回一个字符串用于替换(返回的字符串中不能再引用分组)。

import re

p = re.compile(r'(\w+) (\w+)')  #p是这个正则,匹配到内容后,替换func返回的结果,这个操作会做多次
s = 'i say, hello world!'

def func(m): #m是p的匹配对象(Match对象)
    print("group1:",m.group(1))
    print("group2:",m.group(2))
    return m.group(2).title() +" "+ m.group(1).title()

print(p.sub(func, s))

#执行结果:
group1: i
group2: say
group1: hello
group2: world
Say I, World Hello!	

11.15 re.sub

re.sub(pattern,repl,string,count=0,flags=0)
(1)repl为字符串


>>> re.sub(r"\d+","**","1a2b3c")
'**a**b**c'
>>> re.sub(r"\d+","**","a2b3c4")
'a**b**c**'
>>> re.sub(r"\d+","**","a2b3c4",2)  #替换次数
'a**b**c4'

(2)repl为函数

import re

def multiply(m):
    # 将分组0的值转成整型
v = int(m.group(0))
print(v)
    return str(v * 2)

# 使用multiply方法作为第二个参数,将匹配到的每个数字作为参数传入multiply函数,处理后将返回结果替换为相应字符串
result = re.sub("\d+", multiply, "10 20 30 40 50") 
print(result)	

#执行结果
10
20
30
40
50
20 40 60 80 100
>>> s="1 2 3 4 5"
>>> def func(m):
...     print(m.group())
...     return str(int(m.group())+1)
...
>>> re.sub(r"\d",func,s)
1
2
3
4
5
'2 3 4 5 6'

11.16 pattern.subn

与sub用法一样,只是结果返回一个元组,第一个元素是替换后的新字符串,第二个元素是替换的次数。

11.17 re.subn

与sub用法一样,只是结果返回一个元组,第一个元素是替换后的新字符串,第二个元素是替换的次数

>>> s="^&%today&(is%%fine# day!"
>>> re.subn(r"\W+"," ",s)
(' today is fine day ', 5)

>>> re.subn(r"\d+","*","a1b23c456")
('a*b*c*', 3)
>>> s="1 2 3 4 5"
>>> def func(m):
...     print(m.group())
...     return str(int(m.group())+1)
...
>>> re.subn(r"\d",func,s)
1
2
3
4
5
('2 3 4 5 6', 5)
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值