python中带[和*的正则表达式
我有一个文件,上面有这样的行python中带[和*的正则表达式,python,regex,Python,Regex,我有一个文件,上面有这样的行 variable = epms[something][something] 我需要通过搜索epms找到这些行 目前,我正在尝试: regex = re.compile('[.]*epms\[[.]*\]\[[.]*\][.]*') 但是,这找不到任何匹配项。我做错了什么?尝试此模式epms\[.\]\[.\] Ex: import re with open(filename1) as infile: for line in infile:
variable = epms[something][something]
我需要通过搜索epms找到这些行
目前,我正在尝试:
regex = re.compile('[.]*epms\[[.]*\]\[[.]*\][.]*')
但是,这找不到任何匹配项。我做错了什么?尝试此模式
epms\[.\]\[.\]
Ex:
import re
with open(filename1) as infile:
for line in infile:
if re.search(r"epms\[.*\]\[.*\]", line):
print(line)
尝试此模式
epms\[.\]\[.\]
Ex:
import re
with open(filename1) as infile:
for line in infile:
if re.search(r"epms\[.*\]\[.*\]", line):
print(line)
您可以使用以下模式:
epms\[[^]]+\]\[[^]]+\]
匹配文字子字符串epms
匹配一个\[
[
否定字符集。除[^]]+
以外的任何字符集]
匹配一个\]
]
匹配一个\[
[
否定字符集。除[^]]+
以外的任何字符集]
匹配一个\]
]
import re
mystring = "variable = epms[something][something]"
if re.search(r'epms\[[^]]+\]\[[^]]+\]',mystring):
print (mystring)
您可以使用以下模式:
epms\[[^]]+\]\[[^]]+\]
匹配文字子字符串epms
匹配一个\[
[
否定字符集。除[^]]+
以外的任何字符集]
匹配一个\]
]
匹配一个\[
[
否定字符集。除[^]]+
以外的任何字符集]
匹配一个\]
]
import re
mystring = "variable = epms[something][something]"
if re.search(r'epms\[[^]]+\]\[[^]]+\]',mystring):
print (mystring)
试试这个,在Python3中测试:
>>> s = 'variable = epms[something][something]'
>>> re.match(r'.*epms\[.*\]\[.*\]', s)
<_sre.SRE_Match object; span=(0, 37), match='variable = epms[something][something]'>
>s='variable=epms[something][something]'
>>>重新匹配(r'.*epms\[.\]\[..\]',s)
您不需要方括号来标识“任何字符”。试试这个,在Python3中测试:
>>> s = 'variable = epms[something][something]'
>>> re.match(r'.*epms\[.*\]\[.*\]', s)
<_sre.SRE_Match object; span=(0, 37), match='variable = epms[something][something]'>
>s='variable=epms[something][something]'
>>>重新匹配(r'.*epms\[.\]\[..\]',s)
您不需要方括号来标识“任何字符”。
[.]
匹配文字点字符。您需要删除[]
周围的
。此外,请参阅Try\^*epms[.*?][.*]如果要查找精确的字符串,为什么要使用regex?[.]
匹配文字点字符。您需要删除[]
周围的
。另外,请参阅Try\^*epms[.*?][.*]如果您要查找确切的字符串,为什么要使用regex?感谢您的完整解释!谢谢你的充分解释!