[英]regex in python: how to use variable string in pattern?
I can match a string from a list of string, like this: 我可以从字符串列表中匹配一个字符串,如下所示:
keys = ['a', 'b', 'c']
for key in keys:
if re.search(key, line):
break
the problem is that I would like to match a pattern made from regular expression + string that I would specify. 问题是我想匹配由正则表达式+我要指定的字符串组成的模式。 Something like this:
像这样:
keys = ['a', 'b', 'c']
for key in keys:
if re.search('[^\[]'+key+'[^\]]', line):
break
but this does not work (in this example I would like to match 'a', 'b' and 'c' only if they appear in squared brackets). 但这是行不通的(在此示例中,仅当方括号中出现“ a”,“ b”和“ c”时,我才想匹配它们)。 I think this has to do with raw strings etc, but I cannot find a way to make it work.
我认为这与原始字符串等有关,但我找不到使它起作用的方法。 Suggestions?
有什么建议吗?
EDIT: 编辑:
let's say I want to match a pattern a bit more complicated: 假设我要匹配一个更复杂的模式:
'[^\s*data\.'+key+'\s*=\s*\[(.+)[^\]]'
in order to match the number in brackets: 为了匹配括号中的数字:
data.a = [12343.232 ]
re.search('\['+re.escape(key)+']', line):
this will match [key]
. 这将匹配
[key]
。 Note that re.escape
was added to prevent that characters within key
are interpreted as regex. 请注意,添加了
re.escape
以防止将key
中的字符解释为regex。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.