20180907学习日报-正则二

1.匹配hi开头的单词,只需要匹配一次。s=‘hi ,his name is history!’

import re
s=‘hi ,his name is history!’
print(re.match(r"hi\w*",s))

执行结果:
<_sre.SRE_Match object; span=(0, 2), match=‘hi’>

import re
s=‘hi ,his name is history!’
print(re.search(r"hi\w*",s))

执行结果:
<_sre.SRE_Match object; span=(0, 2), match=‘hi’>

2.匹配hi开头的单词,需要匹配二次。s=‘hi ,his name is history!’

import re
s=‘hi ,his name is history!’
print(re.findall(r"hi\w*",s)[0:2])

执行结果:
[‘hi’, ‘his’]

3.匹配hi开头的单词,需要返回全部匹配结果。s=‘hi ,his name is history!’

import re
s=‘hi ,his name is history!’
print(re.findall(r"hi\w*",s))

执行结果:
[‘hi’, ‘his’, ‘history’]

4.匹配以ing或者noon为结尾的单词。s=‘good morning,good afternoon,good evening’

import re
s=‘good morning,good afternoon,good evening’
print(re.findall(r"\w*ing|noon\b",s))

执行结果:
[‘morning’, ‘noon’, ‘evening’]

5.匹配包含tom的内容(忽略大小写)并返回匹配的个数。s=‘My name is Tom, and you can call me Tommy too’。

import re
s=‘My name is Tom, and you can call me Tommy too,tomorrow’
print(re.findall(r"\w*[t|T]om\w*",s))

执行结果:
[‘Tom’, ‘Tommy’, ‘tomorrow’]

import re
s=‘My name is Tom, and you can call me Tommy too,tomorrow’
print(re.findall(r"\wtom\w",s,re.I))

执行结果:
[‘Tom’, ‘Tommy’, ‘tomorrow’]

6.匹配以in开头单词的后半部分(如integrated–>返回tegrated)。s=‘introduction,i am interesting boy’

import re
s=‘introduction,i am interesting boy’
print(re.findall(r"(?<=in)\w*",s))

执行结果:
[‘troduction’, ‘teresting’]

7.匹配不包含连续字符串abc的单词。s=‘abcddd qweabee ddabc abc cba’

import re
result=[]
s=‘abcddd qweabee ddabc abc cba’
print(re.findall(r"\w+",s))
result1=re.findall(r"\w+",s)
print(re.findall(r"\wabc\w",s))
result2=re.findall(r"\wabc\w",s)
for i in result1:
if i not in result2:
result.append(i)
print(result)

没有想出一个正则能解决的办法

8.匹配网址格式,如www.baidu.com或者https://www.baidu.com/

import re
s=‘https://www.baidu.com/
print(re.findall(r"w{3}.\w*.\w*",s))

执行结果:
[‘www.baidu.com’]

9.匹配指定格式的电话号码,如010-1234-5678或者1234-5678
10.

import re
s = ‘010-1234-5678 1234-567810’
print(re.findall(r"(?:\d{3,4}-)?\d{4}-\d{4,6}",s))

执行结果:
[‘010-1234-5678’, ‘1234-567810’]

10.随机生成10位数字,如果10位数字中有任意3位连续数字,返回666,否则返回0

import re
import random
num = random.randint(1000000000,9999999999)
print(num)
if re.search(r’(\d)\1\1’,str(num)):
print(“666”)
else:
print(“0”)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值