仅从每个Java文件的顶部删除多行注释
我们曾经使用borland starteam工具(mercurial之类的修订/源代码控制系统之一)进行代码管理。无论何时提交代码,工具本身都会将提交的描述放在文件的顶部。 现在我们在代码中有很多类,它们位于每个文件的顶部。 例如:仅从每个Java文件的顶部删除多行注释,java,c#,regex,starteam,Java,C#,Regex,Starteam,我们曾经使用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 di
/*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开头,以$结尾的块。
我已经研究了其他与此问题相关的问题,但这是一个多行注释。正则表达式是一个很好的选择吗
除了编写自己的代码之外,我还可以使用什么工具来删除它
如果正则表达式是唯一快速的解决方案,那么我就陷入了困境
任何帮助都将不胜感激。如果格式完全如您所示,您可以构建一个脆弱的小状态机,如下所示
从枚举开始跟踪状态:
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解析器而不是RegexMultiline注释是尝试解析的难点。考虑<代码> /*东西*更多的东西/惊喜,有一个评论开始在评论*/< /代码>。如果模式总是相同的(如上所示),这只是稍微有点困难,但在一般情况下,您确实需要一个语言解析器。这个Maven插件似乎做了一些非常接近您需要的事情。@umairkhalid:我的答案有用吗?