gpt4 book ai didi

c++ - 正确解析正则表达式中的注释

转载 作者:太空狗 更新时间:2023-10-29 21:16:33 26 4
gpt4 key购买 nike

我正在创建一个编译器,但在处理多行注释 (/* */) 时遇到了注释问题。问题是我的正则表达式需要修复。我相信它所做的是寻找一个开始评论标记(/*),但会接受任何结束评论标记(*/),它甚至可能不是评论范围。

还有一个问题是,在一个字符串中,它仍然会尝试将其注释掉。这个问题我还没有实现,但一些帮助将不胜感激。

我使用的正则表达式是:

[/][*](.|\n)*[*][/]

例子:

输入:

int main(/* text */) {
int i = 0;
/* hello world */
return 1;
}

输出:

int main(

return 1;
}

然后对于字符串,输入将是:

 int main() {
printf("/* hi there */\n");
return 1;
}

输出:

int main() {
printf("\n");
return 1;
}

最佳答案

我不确定您使用的是什么正则表达式库,但您需要所谓的非贪婪匹配

试试这个:

\/\*(.|\n)*?\*\/

.* 之后的 ? 使匹配不贪心

您可以想象这个工作 here .

注意这是Perl-Compatible Regular Expression (PCRE)语法,我假设你正在使用。如果您使用的是 POSIX 正则表达式,这将不起作用。

您也不需要将 /* 放在字符类中 ([...]);你只需要逃避他们。

您还可以使用 PCRE_DOTALL 标志使 . 也匹配 \n\r,这可以简化您的正则表达式。

PCRE_DOTALL
If this bit is set, a dot metacharacter in the pattern matches a char-
acter of any value, including one that indicates a newline. However, it
only ever matches one character, even if newlines are coded as CRLF.
Without this option, a dot does not match when the current position is
at a newline. This option is equivalent to Perl's /s option, and it can
be changed within a pattern by a (?s) option setting. A negative class
such as [^a] always matches newline characters, independent of the set-
ting of this option.

然后,our regex会是:

\/\*.*?\*\/

您还可以使用 PCRE_UNGREEDY 标志使整个正则表达式不贪婪:

PCRE_UNGREEDY

This option inverts the "greediness" of the quantifiers so that they
are not greedy by default, but become greedy if followed by "?". It is
not compatible with Perl. It can also be set by a (?U) option setting
within the pattern.

在这种情况下,this will work :

\/\*.*\*\/

关于c++ - 正确解析正则表达式中的注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34834143/

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