Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
不带花括号的Python正则表达式模式_Python_Regex - Fatal编程技术网

不带花括号的Python正则表达式模式

不带花括号的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.group(3)只匹配没有花括号的代码

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)