Python正则表达式:匹配括号内的括号 [英] Python regex: matching a parenthesis within parenthesis
问题描述
我一直在尝试匹配以下字符串:
I've been trying to match the following string:
string = "TEMPLATES = ( ('index.html', 'home'), ('base.html', 'base'))"
但不幸的是,我对正则表达式的了解非常有限,如您所见,有两个括号需要匹配,以及第二个括号内的内容我尝试使用 re.match("\(w*\)", string)
但它不起作用,任何帮助将不胜感激.
But unfortunately my knowledge of regular expressions is very limited, as you can see there are two parentheses that need to be matched, along with the content inside the second one
I tried using re.match("\(w*\)", string)
but it didn't work, any help would be greatly appreciated.
推荐答案
试试这个:
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))
输出:
index.html <-> home
base.html <-> base
说明:
outer
使用 \(
和 \)
匹配第一组括号;默认情况下,search
找到最长的匹配,给我们最外面的 ( )
对.匹配 m
包含那些外括号之间的内容;其内容对应于outer
的.+
位.
outer
matches the first-starting group of parentheses using \(
and \)
; by default search
finds the longest match, giving us the outermost ( )
pair. The match m
contains exactly what's between those outer parentheses; its content corresponds to the .+
bit of outer
.
innerre
与您的 ('a', 'b')
对完全匹配,再次使用 \(
和 \)
匹配输入字符串中的内容括号,并在 ' '
内使用两个组来匹配那些单引号内的字符串.
innerre
matches exactly one of your ('a', 'b')
pairs, again using \(
and \)
to match the content parens in your input string, and using two groups inside the ' '
to match the strings inside of those single quotes.
然后,我们使用 findall
(而不是 search
或 match
)来获取 innerre
的所有匹配项(而不仅仅是一个).此时 results
是一个对的列表,如打印循环所示.
Then, we use findall
(rather than search
or match
) to get all matches for innerre
(rather than just one). At this point results
is a list of pairs, as demonstrated by the print loop.
更新:要匹配整个内容,您可以尝试以下操作:
Update: To match the whole thing, you could try something like this:
rx = re.compile("^TEMPLATES = \(.+\)")
rx.match(w)
这篇关于Python正则表达式:匹配括号内的括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!