gpt4 book ai didi

c++ - 用于检测分号终止的 C++ for 和 while 循环的正则表达式

转载 作者:IT老高 更新时间:2023-10-28 12:34:59 24 4
gpt4 key购买 nike

在我的 Python 应用程序中,我需要编写一个正则表达式来匹配以分号 ( ;)。例如,它应该匹配这个:

for (int i = 0; i < 10; i++);

...但不是这个:

for (int i = 0; i < 10; i++)

这乍一看似乎微不足道,直到您意识到左括号和右括号之间的文本可能包含其他括号,例如:

for (int i = funcA(); i < funcB(); i++);

我正在使用 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 a parenthesis:
[^()]
| # …or a parenthesised string:
\( # A parenthesised string begins with an opening parenthesis
(?P=balanced)* # …followed by a sequence of balanced substrings
\) # …and ends with a closing parenthesis
)* # Look for a sequence of balanced substrings
\) # Finally, the outer closing parenthesis.
# must end with a semi-colon to match:
\s*;\s*

这对于上述所有情况都非常有效,但是一旦您尝试使 for 循环的第三部分包含一个函数,它就会中断,如下所示:

for (int i = 0; i < 10; doSomethingTo(i));

我认为它会中断,因为只要您在左括号和右括号之间放置一些文本,“平衡”组就会匹配包含文本,因此 (?P=balanced) 部分不会' 不再起作用,因为它不匹配(由于括号内的文本不同)。

在我的 Python 代码中,我使用了 VERBOSE 和 MULTILINE 标志,并像这样创建正则表达式:

REGEX_STR = r"""# 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 a parenthesis:
[^()]
| # …or a parenthesised string:
\( # A parenthesised string begins with an opening parenthesis
(?P=balanced)* # …followed by a sequence of balanced substrings
\) # …and ends with a closing parenthesis
)* # Look for a sequence of balanced substrings
\) # Finally, the outer closing parenthesis.
# must end with a semi-colon to match:
\s*;\s*"""

REGEX_OBJ = re.compile(REGEX_STR, re.MULTILINE| re.VERBOSE)

谁能建议改进这个正则表达式?这对我来说太复杂了。

最佳答案

您可以编写一个非常简单的小程序来执行此操作,而无需使用正则表达式:

  • 设置一个位置计数器pos,使其指向forwhile 之后的左括号之前。
  • 将开括号计数器 openBr 设置为 0
  • 现在继续递增pos,读取各个位置的字符,当你看到一个左括号时递增openBr,当你看到一个右括号时递减它。这将在开始时增加一次,对于“for (”中的第一个左括号,对于中间的一些括号,增加和减少一些,并将其设置回 0 当你的 for 括号关闭时。
  • 所以,当 openBr 再次为 0 时停止。

停止位置是 for(...) 的右括号。现在您可以检查是否有分号。

关于c++ - 用于检测分号终止的 C++ for 和 while 循环的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/524548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com