簡體   English   中英

Python正則表達式:匹配括號內的括號

[英]Python regex: matching a parenthesis within parenthesis

我一直在嘗試匹配以下字符串:

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

但不幸的是,我對正則表達式的了解非常有限,如您所見,有兩個括號需要匹配,以及我嘗試使用re.match("\\(w*\\)", string)但它沒有用,任何幫助將不勝感激。

嘗試這個:

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.+位。

innerre完全匹配您的('a', 'b')對之一,再次使用\\(\\)匹配輸入字符串中的內容括號,並使用' '內的兩組來匹配那些單個引號。

然后,我們使用findall (而不是searchmatch )來獲取innerre所有匹配innerre (而不僅僅是一個)。 此時results是一個對的列表,如打印循環所示。

更新:要匹配整個事情,你可以嘗試這樣的事情:

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

首先,使用\\(不足以匹配括號。Python 通常對其字符串中的某些轉義序列做出反應,這就是為什么它將\\(解釋為簡單的( 。你要么必須寫\\\\(要么使用原始字符串,例如r'\\('r"\\("

其次,當您使用re.match ,您將正則表達式搜索錨定到字符串的開頭。 如果要在字符串中的任何位置查找模式,請使用re.search

就像約瑟夫在他的回答中所說的那樣,你想找到什么並不完全清楚。 例如:

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

將打印

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

編輯:

我更正了, @phoji 是對的:在這種特定情況下,轉義無關緊要。 但是re.matchre.searchre.findall仍然很重要。

如果你的字符串看起來像有效的 Python 代碼,你可以這樣做:

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

您的示例正在尋找開括號后跟零個或多個字母 w 后跟閉括號。 您可能想使用 \\w 而不是 w,但無論如何這在您的情況下不起作用,因為您在開放括號旁邊有非單詞字符。

我認為您應該考慮在逗號處拆分字符串。 你的最終目標是什么?

如果您想驗證括號是否平衡了兩級深,您可以使用以下正則表達式:

import re;

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

pattern = re.compile(r"(?P<expression>\(([^()]*(?P<parenthesis>\()(?(parenthesis)[^()]*\)))*?[^()]*\))")

match = pattern.findall(string)

print(match[0][0])
print(match[1][0])
print(match[2][0])

此正則表達式使用條件語句(?(parenthesis)[^()]*\\))

演示: https : //repl.it/@Konard/ParenthesesExample

最好在這里使用適當的解析模塊,例如pyparsing。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM