我有一些大的c源文件,我想将所有行尾注释与第n个字符对齐。采取以下措施:``
Task<x> DoStuff(...., CancellationToken? ct = null) {
var token = ct ?? CancellationToken.None;
...
}
该函数上方的注释大约为60-70个字符(我们会说70)。所以我希望行结尾注释从第71个字符开始。像这样
//--------------------------------------------------------------------------!
// Unveil Left to Right !
//--------------------------------------------------------------------------!
static void pUnveilL(ulong frame, ulong field)
{
Frame* thisFrame = &Frames[frame] ; // make code more readable
Field* thisField = &Fields[Frames[frame].fields[field]] ; // make code more readable
为了向上舍入,我认为我有查找排序或可以管理它,但我需要一个替换参数来从行中的第n个位置开始注释//。替换部件是否可行?
答案 0 :(得分:1)
您无法使用正则表达式进行 和简单搜索&amp;替换,因为你必须做数学。
这是执行您要执行的操作的算法之一:
int position = 70;
List<string> output = new List<string>();
foreach (string line in File.ReadAllLines(@"C:\Users\me\Desktop\test.txt"))
{
// The line contains comments AND code
if (line.Contains(@"//") && !Regex.IsMatch(line, @"^\s*//"))
{
var matchCollection = Regex.Matches(line, @"(?<code>.*;)\s*(?<comment>\/\/.*)");
string code = matchCollection[0].Groups["code"].Value;
string comment = matchCollection[0].Groups["comment"].Value;
output.Add(code.PadRight(position) + comment);
}
else
{
output.Add(line);
}
}
File.WriteAllLines(@"C:\Users\me\Desktop\out.txt", output);
它是用c#写的,因为它非常接近伪代码,你可以轻松移植它(至少我希望如此)。以下是主要的重要部分(如果您需要更多解释,请不要犹豫):
Regex.IsMatch(line, @"^\s*//")
:找到只是评论的行(?<code>.*;)
:一个命名的捕获组code.PadRight(position)
:PadRigth在字符串右侧添加空白区域,直到position
鉴于此输入:
//--------------------------------------------------------------------------!
// Unveil Left to Right !
//--------------------------------------------------------------------------!
static void pUnveilL(ulong frame, ulong field)
{
Frame* thisFrame = &Frames[frame] ; // make code more readable
Field* thisField = &Fields[Frames[frame].fields[field]] ; // make code more readable
程序输出:
//--------------------------------------------------------------------------!
// Unveil Left to Right !
//--------------------------------------------------------------------------!
static void pUnveilL(ulong frame, ulong field)
{
Frame* thisFrame = &Frames[frame] ; // make code more readable
Field* thisField = &Fields[Frames[frame].fields[field]] ; // make code more readable