gpt4 book ai didi

java - 仅从每个 Java 文件顶部删除多行注释

转载 作者:行者123 更新时间:2023-12-02 10:36:45 25 4
gpt4 key购买 nike

我们曾经使用 borland starteam 工具(一种类似于 Mercurial 的修订/源代码控制系统)来进行代码管理。每当我们提交代码时,工具本身都会在文件顶部放置提交的描述。现在我们在每个文件顶部的代码中有许多类。例如:

/*This is some developer comment at the top of the file*/

/*
* $Log:
* 1 Client Name 1.0 07/11/2012 16:28:54 Umair Khalid did something
* 2 Client Name 1.0 07/11/2012 16:28:54 Umair Khalid again did
* something
* $
*/

public class ABC
{
/*This is just a variable*/
int a = 0;
public int method1()
{
}
}

现在我计划删除每个文件顶部存在的所有此类 starteam 类型的代码。但我不想删除任何文件中的任何其他评论或顶部的任何其他版权评论。我只想删除以 $Log 开头并以 $ 结尾的 block 。我查看了与此问题相关的其他问题,但这是多行评论。正则表达式是一个不错的选择吗?

我可以使用任何实用程序而不是编写自己的代码来删除它吗?

如果正则表达式是唯一的快速解决方案,那么我就陷入困境。

如有任何帮助,我们将不胜感激。

最佳答案

如果格式完全如您所示,您可以构建一个像这样的脆弱的小型状态机。

从枚举开始来跟踪状态:

enum ParseState
{
Normal,
MayBeInMultiLineComment, //occurs after initial /*
InMultilineComment,
}

然后添加以下代码:

     public static void CommentStripper()
{
var text = @"/*This is some developer comment at the top of the file*/
/*
* $Log:
* 1 Client Name 1.0 07/11/2012 16:28:54 Umair Khalid did something
* 2 Client Name 1.0 07/11/2012 16:28:54 Umair Khalid again did
* something
* $
*/

/*
This is not a log entry
*/

public class ABC
{
/*This is just a variable*/
int a = 0;
public int method1()
{
}
}";

//this next line could be File.ReadAllLines to get the text from a file
//or you could read from a stream, line by line.

var lines = text.Split(new[] {"\r\n"}, StringSplitOptions.None);

var buffer = new StringBuilder();
ParseState parseState = ParseState.Normal;
string lastLine = string.Empty;

foreach (var line in lines)
{
if (parseState == ParseState.Normal)
{
if (line == "/*")
{
lastLine = line;
parseState = ParseState.MayBeInMultiLineComment;
}
else
{
buffer.AppendLine(line);
}
}
else if (parseState == ParseState.MayBeInMultiLineComment)
{
if (line == " * $Log:")
{
parseState = ParseState.InMultilineComment;
}
else
{
parseState = ParseState.Normal;
buffer.AppendLine(lastLine);
buffer.AppendLine(line);
}
lastLine = string.Empty;
}
else if (parseState == ParseState.InMultilineComment)
{
if (line == " */")
{
parseState = ParseState.Normal;
}
}

}
//you could do what you want with the string, I'm just going to write it out to the debugger console.
Debug.Write(buffer.ToString());
}

请注意,使用 lastLine 是因为您需要预读一行来确定注释是否是日志条目(这就是 MayBeInMultiLineComment 状态)轨道)。

输出如下:

/*This is some developer comment at the top of the file*/


/*
This is not a log entry
*/

public class ABC
{
/*This is just a variable*/
int a = 0;
public int method1()
{
}
}

关于java - 仅从每个 Java 文件顶部删除多行注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53234511/

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