Python正则表达式:匹配括号内的括号

编程入门 行业动态 更新时间:2024-10-25 17:14:32
本文介绍了Python正则表达式:匹配括号内的括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在尝试匹配以下字符串:

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正则表达式:匹配括号内的括号

本文发布于:2023-11-03 12:25:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555131.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:括号   括号内   正则表达式   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!