不带花括号的Python正则表达式模式
如何返回没有大括号的字符串? 例如,在下面的代码中,我想要pattern.group(3)只匹配没有花括号的代码不带花括号的Python正则表达式模式,python,regex,Python,Regex,如何返回没有大括号的字符串? 例如,在下面的代码中,我想要pattern.group(3)只匹配没有花括号的代码 pattern = re.search('(.*)#ifdef (.*?)if(.*?)#endif(.*?){(.*?)}(.*)',codigo,re.DOTALL) 所以 与之匹配,以及 #ifdef SIZE == 1 if(x == 2){ //lines of code 2
pattern = re.search('(.*)#ifdef (.*?)if(.*?)#endif(.*?){(.*?)}(.*)',codigo,re.DOTALL)
所以
与之匹配,以及
#ifdef SIZE == 1
if(x == 2){
//lines of code 2
}
#endif
不是。我只是将整个花括号部分围在一个非捕获组中,并将其设置为可选。这样,在其他组已填充的情况下,您仍然会得到一个正则表达式匹配对象
'(.*)#ifdef (.*?)if(.*?)#endif(.*?)(?:{(.*?)})?(.*)'
事实上,我在找这样的东西
re.search('(.*)#ifdef (.*?)if([^{]*?)#endif(.*?){(.*?)}(.*)',codigo,re.DOTALL)
所以,我保证组(3)中没有任何{。为什么不检查返回的组?
re.search('(.*)#ifdef (.*?)if([^{]*?)#endif(.*?){(.*?)}(.*)',codigo,re.DOTALL)