在我的Python应用程序中,我需要编写一个匹配C++ for或while循环的正则表达式,该循环使用分号(;).例如,它应匹配此:
for (int i = 0; i < 10; i++);
Run Code Online (Sandbox Code Playgroud)
......但不是这个:
for (int i = 0; i < 10; i++)
Run Code Online (Sandbox Code Playgroud)
这看起来很琐事,直到您意识到开括号和右括号之间的文本可能包含其他括号,例如:
for (int i = funcA(); i < funcB(); i++);
Run Code Online (Sandbox Code Playgroud)
我正在使用python.re模块.现在我的正则表达式看起来像这样(我已经留下了我的评论,所以你可以更容易理解):
# match any line that begins with a "for" or "while" statement:
^\s*(for|while)\s*
\( # match the initial opening parenthesis
# Now make a named group 'balanced' which matches a balanced substring.
(?P<balanced>
# A balanced substring is either something that is not …Run Code Online (Sandbox Code Playgroud) 让我们有一个文本,我们希望在双引号之间匹配所有字符串; 但在这些双引号内,可以引用双引号.例:
"He said \"Hello\" to me for the first time"
Run Code Online (Sandbox Code Playgroud)
使用正则表达式,您如何有效地匹配它?
我对RegEx有一点了解,但此刻,它远远超出了我的能力.
我需要帮助才能在最后一个没有匹配括号的开括号之后立即找到文本/表达式.
这是开发中的开源软件(Object Pascal)的CallTip.
下面是一些例子:
------------------------------------
Text I need
------------------------------------
aaa(xxx xxx
aaa(xxx, xxx
aaa(xxx, yyy xxx
aaa(y=bbb(xxx) y=bbb(xxx)
aaa(y <- bbb(xxx) y <- bbb(xxx)
aaa(bbb(ccc(xxx xxx
aaa(bbb(x), ccc(xxx xxx
aaa(bbb(x), ccc(x) bbb(x)
aaa(bbb(x), ccc(x), bbb(x)
aaa(?, bbb(?? ??
aaa(bbb(x), ccc(x)) ''
aaa(x) ''
aaa(bbb( ''
------------------------------------
For all text above the RegEx proposed by @Bohemian
(?<=\()(?=([^()]*\([^()]*\))*[^()]*$).*?(?=[ ,]|$)(?! <-)(?<! <-)
matches all cases.
For the below (I found these cases when implementing the RegEx in the software) not
------------------------------------
New …Run Code Online (Sandbox Code Playgroud)