加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式检测分号结束的C for&while循环

发布时间:2020-12-14 06:39:28 所属栏目:百科 来源:网络整理
导读:在我的Python应用程序中,我需要编写一个正则表达式,该表达式匹配已经用分号(;)终止的C for或while循环。例如,它应该匹配: for (int i = 0; i 10; i++); …但不是这样: for (int i = 0; i 10; i++) 这看起来很琐碎,直到你意识到开始和结束括号之间的文
在我的Python应用程序中,我需要编写一个正则表达式,该表达式匹配已经用分号(;)终止的C for或while循环。例如,它应该匹配:
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 =平衡)部分不再工作,因为它不会匹配(由于括号内的文本不同的事实)。

在我的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,使其指向刚好在for或while之前的开头括号。
>将开括号计数器openBr设置为0。
>现在继续递增pos,读取相应位置处的字符,并在看到开括号时增加openBr,并在看到结束括号时递减。这将增加一次在开始,对于第一个开头括号“for(”,增加和减少一些括号之间,并设置为0,当您的括号关闭时。
>所以,当openBr再次为0时停止。

停止位置是for(…)的结束括号。现在你可以检查是否有一个分号跟随或不。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读