簡體   English   中英

正則表達式匹配負后瞻、遞歸模式和負前瞻

[英]Regex match with negative lookbehind, recursive pattern and negative lookahead

我需要匹配這個:

void function{ {  {  } }}   

(帶平衡括號的函數定義)但不是這個

static stTLookupTable RxTable[MAX]={
     
    {zero, one},{zero, one},{zero, one}};

我試圖用(?<?[[=])({((?>[^{}]+|(?R))*)})(;!;)匹配環視,但這匹配 {zero, one} 在變量聲明中。

(?<![[=]){((?>[^{}]+|(?R))*)}[^;]$ doesn't work either.

簡而言之,我需要它來匹配 function 定義,但不是數組聲明,假設數組初始化以]=開頭。 有誰知道如何單獨匹配 function 定義?

PS: {((?>[^{}]+|(?R))*)}匹配平衡括號

假設您使用的是 PyPi regex模塊,您可以使用

import regex
text = """void function{ {  {  } }}   
static stTLookupTable RxTable[MAX]={
     
    {zero, one},{zero, one},{zero, one}};"""

print( [x.group(3) for x in regex.finditer(r'=\s*({(?>[^{}]+|(?1))*})(*SKIP)(*F)|({((?>[^{}]+|(?2))*)})', text)] )
# => [' {  {  } }']

在線查看 Python 演示

詳情

  • =\s*({(?>[^{}]+|(?1))*})(*SKIP)(*F)
    • = - a =字符
    • \s* - 零個或多個空格
    • ({(?>[^{}]+|(?1))*}) - 平衡{...}之間的 substring
    • (*SKIP)(*F) - 跳過匹配並從失敗重新開始搜索 position
  • | - 或者
  • ({((?>[^{}]+|(?2))*)}) - 第 2 組(技術,用於遞歸):
    • {((?>[^{}]+|(?2))*)} - 匹配帶有平衡花括號的{...} substring。

您需要從比賽中返回第 3 組。

使用(?R)將遞歸整個模式。

您可以匹配void function或除[MAX]=之外的任何內容,方法是匹配單詞字符\w+或使用[^\s{}=,]+排除允許的字符,並使用 PyPi 正則表達式模塊遞歸第一個子模式(?1)

\w+(?: \w+)*({(?:[^{}]++|(?1))*})

解釋

  • \w+(?: \w+)*匹配{之前的 1 個或多個單詞
  • (捕獲組 1
    • {(?:[^{}]++|(?1))*}匹配開始和結束卷曲的遞歸第一個子模式(?1)
  • )關閉第 1 組

正則表達式演示| Python 演示

import regex

pattern = r"\w+(?: \w+)*({(?:[^{}]++|(?1))*})"

s = ("void function{ {  {  } }} \n\n\n"
    "static stTLookupTable RxTable[MAX]={\n"
    "     \n"
    "    {zero, one},{zero, one},{zero, one}};")

matches = regex.finditer(pattern, s)

for matchNum, match in enumerate(matches, start=1):    
    print (match.group())

Output

void function{ {  {  } }}

要刪除{...}部分:

import regex

pattern = r"(\w+(?: \w+))({(?:[^{}]++|(?2))*})"

s = ("void function{ {  {  } }} \n\n\n"
    "static stTLookupTable RxTable[MAX]={\n"
    "     \n"
    "    {zero, one},{zero, one},{zero, one}};")

print(regex.sub(pattern, r"\1", s))

查看另一個python 演示

暫無
暫無

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

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