Find number and replace + 1

拟墨画扇 提交于 2021-02-08 10:33:36

问题


I have a large file with a list of objects that have an incrementing page # ie

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

I can find each instance of page: # with page: (\d) in vscode's ctrl+f finder. How would I replace each of these numbers with # + 1?


回答1:


It's not possible to perform arithmetic with regex. I use LINQPad to execute these small kind of scripts. An example of how I would do it is in the c# program below.

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);
    }
}

I also took the liberty of changing your regex to the one below.

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.



回答2:


It can be done rather easily in vscode using one of emmet's built-in commands:

Emmet: Increment by 1
  1. Use your regex to find all the page: \d+ in your file.
  2. Ctrl-Shift-L to select all those occurrences.
  3. Trigger the Emmet: Increment by 1 command.

Here is a demo:




回答3:


You could do that in Ruby as follows.

FileIn  = "in"
FileOut = "out"

File let's construct a sample file (containing 37 characters).

File.write FileIn, "[\n{page: 1},\n{page: 2},\n{page: 33}\n]\n"
  #=> 37

We may now read the input file FileIn, convert it and write it to a new file FileOut.

File.write(FileOut, File.read(FileIn).
     gsub(/\{page: (\d+)\}/) { "{page: #{$1.next}}" })

Let's look at what's be written.

puts File.read(FileOut)
[
{page: 2},
{page: 3},
{page: 34}
]

I've gulped the entire file, made the changes in memory and spit out the modified file. If the original file were large this could be easily modified to read from and write to the files line-by-line.



来源:https://stackoverflow.com/questions/55624208/find-number-and-replace-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!