首页 > 技术文章 > python re:正则表达式中使用变量

zhiminyu 2020-12-17 14:57 原文

参考: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\\)')

附正则表达式语法:网址

推荐阅读