gpt4 book ai didi

regex - 只查找多行 C 注释,不查找单行 C 注释

转载 作者:行者123 更新时间:2023-12-05 09:29:43 32 4
gpt4 key购买 nike

假设我有这段文字:

cat file
/* comment */ not a comment /* another comment */

/* delete this *
/* multiline *
/* comment */

/*************
/* and this *
/************/
The End

我可以使用带有条件 perl 吗? : 只删除多行注释:

perl -0777 -pE 's/(\/\*(?:\*(?!\/)|[^*])*\*\/)/($1=~qr"\R") ? "" : $1/eg;' file

打印:

/* comment */ not a comment /* another comment */




The End

没有条件:

perl -0777 -pE 's/(\/\*(?:\*(?!\/)|[^*])*\*\/)//g;' file
not a comment




The End

有没有办法仅使用正则表达式删除多行 C 样式注释?即,不在替换中使用 perl 条件代码?

最佳答案

你可以使用

perl -0777 -pe 's~/\*(?:(?!\*/|/\*).)*\R(?s).*?\*/~~g' file

模式匹配

  • /\* - 一个 /*字符串
  • (?:(?!\*/|/\*).)* - 除换行符以外的零个或多个字符,每个字符都不是 */ 的起始字符和 /*字符序列
  • \R - 换行序列
  • (?s) - 现在,.也将匹配换行符
  • .*? - 尽可能少的零个或多个字符
  • \*/ - 一个 */子串。

参见 regex demo .

关于regex - 只查找多行 C 注释,不查找单行 C 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70453039/

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