我一直在尝试匹配以下字符串:
string = "TEMPLATES = ( ('index.html', 'home'), ('base.html', 'base'))"
Run Code Online (Sandbox Code Playgroud)
但不幸的是,我对正则表达式的了解非常有限,因为你可以看到有两个括号需要匹配,以及我尝试使用的第二个内容,re.match("\(w*\)", string)但它没有用,任何帮助都将非常感激.
pho*_*oji 29
试试这个:
import re
w = "TEMPLATES = ( ('index.html', 'home'), ('base.html', 'base'))"
# find outer parens
outer = re.compile("\((.+)\)")
m = outer.search(w)
inner_str = m.group(1)
# find inner pairs
innerre = re.compile("\('([^']+)', '([^']+)'\)")
results = innerre.findall(inner_str)
for x,y in results:
print("%s <-> %s" % (x,y))
Run Code Online (Sandbox Code Playgroud)
输出:
index.html <-> home
base.html <-> base
Run Code Online (Sandbox Code Playgroud)
说明:
outer使用\(和匹配第一组括号\); 默认情况下search找到最长匹配,给我们最外面的( )一对.匹配m包含那些外括号之间的确切内容; 其内容对应.+的位outer.
innerre恰好匹配您的一('a', 'b')对,再次使用\(和\)匹配输入字符串中的内容parens,并使用其中的两个组' '来匹配这些单引号内的字符串.
然后,我们使用findall(而不是search或match)得到所有比赛innerre(而不仅仅是一个).此时results是对的列表,如打印循环所示.
更新:为了匹配整个事情,你可以尝试这样的事情:
rx = re.compile("^TEMPLATES = \(.+\)")
rx.match(w)
Run Code Online (Sandbox Code Playgroud)
首先,使用\(不足以匹配括号.Python通常会对其字符串中的某些转义序列做出反应,这就是它解释\(为简单的原因(.您可能必须编写\\(或使用原始字符串,例如r'\('或r"\(".
其次,当您使用时re.match,您将正则表达式搜索锚定到字符串的开头.如果要在字符串中的任何位置查找模式,请使用re.search.
就像约瑟夫在他的回答中所说,你想要找到的并不完全清楚.例如:
string = "TEMPLATES = ( ('index.html', 'home'), ('base.html', 'base'))"
print re.findall(r'\([^()]*\)', string)
Run Code Online (Sandbox Code Playgroud)
["('index.html', 'home')", "('base.html', 'base')"]
Run Code Online (Sandbox Code Playgroud)
编辑:
我坚持认为,@ phooji是对的:在这种特殊情况下,逃避是无关紧要的.但re.match相对re.search或re.findall仍然很重要.