【脚本语言系统】关于Python正则表达式sys.re, 你需要知道的事

本文通过实例演示了正则表达式的多种用法,包括匹配特定位置的文本、替换字符串、利用特殊字符进行模式匹配以及使用限定符进行复杂匹配。通过这些例子,读者可以了解如何在Python中使用re模块进行文本搜索、替换和解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何使用正则表达式sys.re

# -*- coding:utf-8 -*-
import re
# use the ^ and $
s = "HELLO WORLD"
print re.findall(r"^hello",s)
print re.findall(r"^hello",s,re.I)
print re.findall("WORLD$",s)
print re.findall(r"wORld$",s,re.I)
print re.findall(r"\b\w+\b",s)
[]
['HELLO']
['WORLD']
['WORLD']
['HELLO', 'WORLD']
# -*- coding:utf-8 -*-
import re
# replace the string
s = "hello world"
print re.sub("hello","hi",s)
print re.sub("hello","hi",s[-4:])
print re.sub("world","China",s[-5:])
hi world
orld
China
# -*- coding:utf-8 -*-
import re
# use the special character
s = "嗨 WORLD2"
print "replace char: "+re.sub(r"\w","hi",s)
print "match times: "+str(re.subn(r"\w", "hi", s)[1])
print "replace nonumchar: "+re.sub(r"\W", "hi", s)
print "match times: "+str(re.subn(r"\W", "hi", s)[1])
print "replace blank: "+re.sub(r"\s", "* ", s)
print "match times: "+str(re.subn(r"\s", "*", s)[1])
print "replace nonblankchar: "+re.sub(r"\S","hi",s)
print "match times: "+str(re.subn(r"\S", "hi", s)[1])
print "replace num: "+re.sub(r"\d", "2.0", s)
print "match times: "+str(re.subn(r"\d", "2.0", s)[1])
print "replace nonum: "+re.sub(r"\D", "hi", s)
print "match times: "+str(re.subn(r"\D", "hi", s)[1])
print "replace anychar: "+re.sub(r".", "hi", s)
print "match times: "+str(re.subn(r".", "hi", s)[1])
replace char: 嗨 hihihihihihi
match times: 6
replace nonumchar: hihihihiWORLD2
match times: 4
replace blank: 嗨* WORLD2
match times: 1
replace nonblankchar: hihihi hihihihihihi
match times: 9
replace num: 嗨 WORLD2.0
match times: 1
replace nonum: hihihihihihihihihi2
match times: 9
replace anychar: hihihihihihihihihihi
match times: 10
# -*- coding:utf-8 -*-
import re
# use the qualifier
tel1 = "0791-1234567"
print re.findall(r'\d{3}-\d{8}|\d{4}-\d{7}', tel1)
tel2 = "010-12345678"
print re.findall(r'\d{3}-\d{8}|\d{4}-\d{7}', tel2)
tel3 = "(010)12345678"
print re.findall(r'[\(]?\d{3}[\)-]?\d{8}|[\(]?\d{4}[\)-]?\d{7}', tel3)
['0791-1234567']
['010-12345678']
['(010)12345678']

什么是正则表达式sys.re

正则表达式用于搜索、替换和解析字符串。
Python提供了re模块实现正则表达式的验证。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值