gpt4 book ai didi

java - 如何用sed删除Java项目的注释?

转载 作者:太空宇宙 更新时间:2023-11-04 13:27:51 25 4
gpt4 key购买 nike

我有一个 Java 项目,其中有 JavaDoc 注释

/** ... */

其他多行注释

/* ... */

行评论

// ...

以及我自己的“解释性评论”

//* ...

当我发布代码时,我希望删除所有行注释 - 但不是其他注释。我想我会用 sed 来做到这一点,但到目前为止我还没有成功。我正在尝试以下操作:

#!/bin/bash

while read -d $'\0' findfile ; do
echo "${findfile}"
mv "${findfile}" "${findfile}".veryold
cat "${findfile}".veryold | sed -e 's|//[^\*"]*[^"]*||' -e 's/[ ^I]*$//' | grep -A1 . | grep -v '^--$' > "${findfile}"
rm -f "${findfile}".veryold
done < <(find "${1}" -type f -print0)

我做错了什么?请注意,不应删除 "..." 中的 //,因为它们可能是 URL 的一部分。

关键部分是

-e 's|//[^\*"]*[^"]*||'

最佳答案

对于如下所示的测试文件:

/** This should stay */
/* And this
* should stay
* as well */
// This one should be removed
//* But this one should stay
code here // This part should go, but not the next line
"http://test.com"
code here //* This should stay

你可以这样做:

$ sed '\#^//[^*]#d;s#//[^*"][^"]*$##' test.java
/** This should stay */
/* And this
* should stay
* as well */
//* But this one should stay
code here
"http://test.com"
code here //* This should stay

第一个表达式 \#^//[^*]#d 删除所有以 // 开头的行(但不删除 //*)。这是为了避免在删除整行时在输出中出现空行。

第二个表达式 s#//[^*"][^"]*$##// 开始匹配(但不是 //*//"),直到行尾,除非 // 和行尾之间有 "

您的表达式 s|//[^\*"]*[^"]*|| 的作用几乎相同,除了:

  • 不需要对括号表达式中的字符进行转义; [\*] 匹配 \*
  • 您希望第一个括号表达式仅匹配一次,而不是零次或多次;您的表达式确实匹配//*
  • 您不会锚定在行尾,因此此表达式会在所有位置匹配 // 并将其删除,即使后面跟着 "*

对于行尾零长度注释的特殊情况,

code here //

如果您想要删除 //,则必须添加第三个替换 s#//$/#,因为现有替换需要 // 之后至少有一个字符。

请注意,这并不是非常干净,因为它可能会在行尾留下无用的空格,但这可以通过 s/[[:space:]]*$/$/ 轻松修复。

关于java - 如何用sed删除Java项目的注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32485397/

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