我一直在尝试匹配以下字符串:
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 = repile("\((.+)\)") m = outer.search(w) inner_str = m.group(1) # find inner pairs innerre = repile("\('([^']+)', '([^']+)'\)") 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 = repile("^TEMPLATES = \(.+\)") rx.match(w)更多推荐
Python正则表达式:匹配括号内的括号
发布评论