我有一个大文件,其中包含一个具有递增页面的对象列表#即
[
{page: 1},
{page: 2},
{page: 3}
]
我可以在vscode的ctrl + f finder中找到page: #
的每个实例和page: (\d)
。如何用#+ 1替换这些数字?
用正则表达式执行算术是不可能的。我使用LINQPad来执行这些小型脚本。我将如何做到的一个例子是在下面的c#程序中。
void Main()
{
var basePath = @"C:\";
// Get all files with extension .cs in the directory and all its subdirectories.
foreach (var filePath in Directory.GetFiles(basePath, "*.cs", SearchOption.AllDirectories))
{
// Read the content of the file.
var fileContent = File.ReadAllText(filePath);
// Replace the content by using a named capture group.
// The named capture group allows one to work with only a part of the regex match.
var replacedContent = Regex.Replace(fileContent, @"page: (?<number>[0-9]+)", match => $"page: {int.Parse(match.Groups["number"].Value) + 1}");
// Write the replaced content back to the file.
File.WriteAllText(filePath, replacedContent);
}
}
我也冒昧地将你的正则表达式更改为下面的正则表达式。
page: (?<number>[0-9]+)
page: matches with "page: " literally.
(?<number> is the start of a named capture group called number. We can then use this group during replacement.
[0-9]+ matches a number between 0 and 9 one to infinite times. This is more specific than using \d as \d also matches other number characters.
The + makes it match more than on digit allowing for the number 10 and onwards.
) is the end of a named capture group.
您可以在Ruby中执行以下操作。
FileIn = "in"
FileOut = "out"
文件让我们构造一个示例文件(包含37
字符)。
File.write FileIn, "[\n{page: 1},\n{page: 2},\n{page: 33}\n]\n"
#=> 37
我们现在可以读取输入文件FileIn
,将其转换并将其写入新文件FileOut
。
File.write(FileOut, File.read(FileIn).
gsub(/\{page: (\d+)\}/) { "{page: #{$1.next}}" })
让我们来看看写的是什么。
puts File.read(FileOut)
[
{page: 2},
{page: 3},
{page: 34}
]
我已经吞下了整个文件,在内存中进行了更改并吐出了修改后的文件。如果原始文件很大,可以很容易地修改它以逐行读取和写入文件。