找到数字并替换+ 1

问题描述 投票:0回答:3

我有一个大文件,其中包含一个具有递增页面的对象列表#即

[
{page: 1},
{page: 2},
{page: 3}
]

我可以在vscode的ctrl + f finder中找到page: #的每个实例和page: (\d)。如何用#+ 1替换这些数字?

regex visual-studio-code
3个回答
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.

0
投票

使用emmet的内置命令之一,可以在vscode中轻松完成它:

Emmet: Increment by 1
  1. 使用正则表达式查找文件中的所有page: \d+
  2. Ctrl-Shift-L选择所有这些事件。
  3. 触发Emmet: Increment by 1命令。

这是一个演示:

Emmet:Increment buy 1


0
投票

您可以在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}
]

我已经吞下了整个文件,在内存中进行了更改并吐出了修改后的文件。如果原始文件很大,可以很容易地修改它以逐行读取和写入文件。

© www.soinside.com 2019 - 2024. All rights reserved.