python re:正则表达式中使用变量
参考:https://www.cnblogs.com/songbiao/p/12422632.html
Python中正则表达式的写法,核心就是一个字符串。如下:re.compile(r'表达式')
所以,如果要在正则表达式中包含变量,那么就可以用{}.format语法,类似string中包含变量的处理方法,当然要确保变量为string型。如下:re.compile(r'expression' + var + 'expression')
re.compile(r'expression(%s)expression' %var)
re.compile(r'expression{}expression'.format(var))
有用的正则表达式网页工具和手册:
正则表达式手册
推荐regexr
参考:https://blog.csdn.net/mifaxie/article/details/79351737
正则表达写法:
re.compile(r’表达式’)
包含变量的正则表达式写法
re.compile(r’表达式’+变量+’表达式’)
re.compile(r’表达式(%s)表达式’ %变量)
示例代码:
url = "oreilly.com"
regex3 = re.compile(r"^((/|.)*(%s))" %url)
regex4 = re.compile(r"^((/|.)*oreilly.com)")
regex5 = re.compile(r"^((/|.)*"+ url +')')
string3 = '/oreilly.com/baidu.com'
mo3 = regex3.search(string3)
mo4 = regex4.search(string3)
mo5 = regex5.search(string3)
print(mo3.group())
print(mo4.group())
print(mo5.group())
输出结果如下:
/oreilly.com
/oreilly.com
/oreilly.com
[Finished in 1.3s]
参考:https://www.cnblogs.com/Atanisi/p/8536046.html
我们有时想把变量放进正则表达式中来匹配想要的结果。Python中使用 re.compile(r''+变量+''),其中正则表达式中的“变量”应为字符串形式。
1 import re 2 regex_test_output = re.compile('Test net output #(\d+): (\S+) = ([.\deE+-]+)') 3 regex_test_output
得到结果
re. compile (r 'Test net output #(\d+): (\S+) = ([.\deE+-]+)' , re. UNICODE ) |
可以看到,Python是将正则表达式用字符串表示的,格式为 r'正则表达式 '
正则表达式使用变量例子:
1 regex_test = [] 2 for i in range(5): 3 regex_test.append(re.compile(r'Iteration (\d+), Testing net \(#' + str(i) + '\)')) 4 print(regex_test[i])
结果为
re. compile ( 'Iteration (\\d+), Testing net \\(#0\\)' ) re. compile ( 'Iteration (\\d+), Testing net \\(#1\\)' ) re. compile ( 'Iteration (\\d+), Testing net \\(#2\\)' ) re. compile ( 'Iteration (\\d+), Testing net \\(#3\\)' ) re. compile ( 'Iteration (\\d+), Testing net \\(#4\\)' ) |
附正则表达式语法:网址
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)