繁体   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