Python regex:在括号内匹配括号

时间:2021-09-16 23:37:00

I've been trying to match the following string:

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

string = "TEMPLATES = ( ('index.html', 'home'), ('base.html', 'base'))"

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.

但不幸的是,我对正则表达式的了解非常有限,因为您可以看到,有两个括号需要匹配,以及第二个我尝试使用re.match的内容(“\(w*\)”(弦乐)但它不管用,任何帮助都将非常感谢。

5 个解决方案

#1


23  

Try this:

试试这个:

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))

Output:

输出:

index.html <-> home
base.html <-> base

Explanation:

解释:

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.

外部匹配使用\(和\)的第一个开始的圆括号组;默认情况下,搜索会找到最长的匹配,并给出最外层()对。匹配m包含了外括号之间的值;它的内容对应于外部。

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.

innerre与您的('a'、'b')对匹配,再次使用\(和\)来匹配输入字符串中的内容parens,并使用' ' '中的两个组来匹配这些单引号中的字符串。

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.

然后,我们使用findall(而不是搜索或匹配)获取innerre的所有匹配(而不仅仅是一个)。此时,结果是一对的列表,如print循环所示。

Update: To match the whole thing, you could try something like this:

更新:为了匹配整个内容,你可以尝试以下方法:

rx = re.compile("^TEMPLATES = \(.+\)")
rx.match(w)

#2


7  

First of all, using \( isn't enough to match a parenthesis. Python normally reacts to some escape sequences in its strings, which is why it interprets \( as simple (. You would either have to write \\( or use a raw string, e.g. r'\(' or r"\(".

首先,使用\(不足以匹配括号)。Python通常对字符串中的一些转义序列作出反应,这就是为什么它解释\(as simple())。你可能需要写\(或者使用一个原始的字符串,例如r'\(或r'\))。

Second, when you use re.match, you are anchoring the regex search to the start of the string. If you want to look for the pattern anywhere in the string, use re.search.

其次,当您使用re.match时,您正在将regex搜索锚定到字符串的开头。如果您想在字符串中的任何位置查找模式,请使用re.search。

Like Joseph said in his answer, it's not exactly clear what you want to find. For example:

就像约瑟夫在他的回答中说的,你不清楚你想要找到什么。例如:

string = "TEMPLATES = ( ('index.html', 'home'), ('base.html', 'base'))"
print re.findall(r'\([^()]*\)', string)

will print

将打印

["('index.html', 'home')", "('base.html', 'base')"]

EDIT:

编辑:

I stand corrected, @phooji is right: escaping is irrelevant in this specific case. But re.match vs. re.search or re.findall is still important.

我纠正了,@phooji是对的:在这个特定的情况下,逃跑是无关紧要的。但是re.match vs. re.search或re.findall仍然很重要。

#3


2  

If your strings look like valid Python code anyways you can do this:

如果您的字符串看起来像有效的Python代码,那么您可以这样做:

import ast
var, s = [part.strip() for part in 
     "TEMPLATES = ( ('index.html', 'home'), ('base.html', 'base'))".split('=')]
result= ast.literal_eval(s)

#4


1  

Your sample is looking for open paren followed by zero or more letter w followed by close paren. You probably want to use \w instead of w, but that won't work in your case anyway, because you have non-word characters next to the open paren.

您的示例是寻找开放的paren,后面是0或更多的字母w,后面是close paren。您可能想要使用\w而不是w,但无论如何这在您的情况下都行不通,因为在打开的paren旁边有非单词字符。

I think you should consider splitting the string at the commas instead. What is your final objective?

我想你应该考虑用逗号分开字符串。你的最终目标是什么?

#5


-2  

Better use proper parsing module like pyparsing here.

最好在这里使用正确的解析模块,如pyparser。

#1


23  

Try this:

试试这个:

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))

Output:

输出:

index.html <-> home
base.html <-> base

Explanation:

解释:

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.

外部匹配使用\(和\)的第一个开始的圆括号组;默认情况下,搜索会找到最长的匹配,并给出最外层()对。匹配m包含了外括号之间的值;它的内容对应于外部。

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.

innerre与您的('a'、'b')对匹配,再次使用\(和\)来匹配输入字符串中的内容parens,并使用' ' '中的两个组来匹配这些单引号中的字符串。

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.

然后,我们使用findall(而不是搜索或匹配)获取innerre的所有匹配(而不仅仅是一个)。此时,结果是一对的列表,如print循环所示。

Update: To match the whole thing, you could try something like this:

更新:为了匹配整个内容,你可以尝试以下方法:

rx = re.compile("^TEMPLATES = \(.+\)")
rx.match(w)

#2


7  

First of all, using \( isn't enough to match a parenthesis. Python normally reacts to some escape sequences in its strings, which is why it interprets \( as simple (. You would either have to write \\( or use a raw string, e.g. r'\(' or r"\(".

首先,使用\(不足以匹配括号)。Python通常对字符串中的一些转义序列作出反应,这就是为什么它解释\(as simple())。你可能需要写\(或者使用一个原始的字符串,例如r'\(或r'\))。

Second, when you use re.match, you are anchoring the regex search to the start of the string. If you want to look for the pattern anywhere in the string, use re.search.

其次,当您使用re.match时,您正在将regex搜索锚定到字符串的开头。如果您想在字符串中的任何位置查找模式,请使用re.search。

Like Joseph said in his answer, it's not exactly clear what you want to find. For example:

就像约瑟夫在他的回答中说的,你不清楚你想要找到什么。例如:

string = "TEMPLATES = ( ('index.html', 'home'), ('base.html', 'base'))"
print re.findall(r'\([^()]*\)', string)

will print

将打印

["('index.html', 'home')", "('base.html', 'base')"]

EDIT:

编辑:

I stand corrected, @phooji is right: escaping is irrelevant in this specific case. But re.match vs. re.search or re.findall is still important.

我纠正了,@phooji是对的:在这个特定的情况下,逃跑是无关紧要的。但是re.match vs. re.search或re.findall仍然很重要。

#3


2  

If your strings look like valid Python code anyways you can do this:

如果您的字符串看起来像有效的Python代码,那么您可以这样做:

import ast
var, s = [part.strip() for part in 
     "TEMPLATES = ( ('index.html', 'home'), ('base.html', 'base'))".split('=')]
result= ast.literal_eval(s)

#4


1  

Your sample is looking for open paren followed by zero or more letter w followed by close paren. You probably want to use \w instead of w, but that won't work in your case anyway, because you have non-word characters next to the open paren.

您的示例是寻找开放的paren,后面是0或更多的字母w,后面是close paren。您可能想要使用\w而不是w,但无论如何这在您的情况下都行不通,因为在打开的paren旁边有非单词字符。

I think you should consider splitting the string at the commas instead. What is your final objective?

我想你应该考虑用逗号分开字符串。你的最终目标是什么?

#5


-2  

Better use proper parsing module like pyparsing here.

最好在这里使用正确的解析模块,如pyparser。