正确解析正则表达式

时间:2016-01-17 01:35:11

标签: c++ c regex

我正在创建编译器,在处理多行注释(/* */)时无法处理注释。问题是我的正则表达式需要修复。我认为它的作用是寻找一个开放的评论标记(/*),但会接受任何结束评论标记(*/),它甚至可能不属于评论范围。

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

我正在使用的正则表达式是:

[/][*](.|\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;
} 

1 个答案:

答案 0 :(得分:3)

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

试试这个:

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

?之后.*匹配 ungreedy

您可以将此工作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

\/\*.*\*\/
相关问题