我们曾经使用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开始并以$结尾的块。 我已经看过其他与此问题相关的问题,但这是多行注释。正则表达式将是一个很好的选择吗?
有什么我可以使用的实用工具,而不是编写我自己的代码来删除的吗?
如果正则表达式是唯一的快速解决方案,那么我就呆在那里。
任何帮助将不胜感激。
答案 0 :(得分:1)
如果显示的格式完全是 ,则可以构建一个像这样的易碎小状态机。
从枚举开始跟踪状态:
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()
{
}
}