查找数字并替换 + 1 [英] Find number and replace + 1
本文介绍了查找数字并替换 + 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个大文件,其中包含一个页面递增的对象列表#ie
<预><代码>[{页面:1},{第2页},{页面:3}]我可以在 vscode 的 ctrl+f 查找器中找到 page: #
和 page: (\d)
的每个实例.我将如何用 # + 1 替换这些数字中的每一个?
解决方案
无法使用正则表达式执行算术运算.我使用 LINQPad 来执行这些小脚本.下面的 c# 程序是我将如何做的一个示例.
void Main(){var basePath = @"C:\";//获取目录及其所有子目录中所有扩展名为 .cs 的文件.foreach (var filePath in Directory.GetFiles(basePath, "*.cs", SearchOption.AllDirectories)){//读取文件内容.var fileContent = File.ReadAllText(filePath);//使用命名的捕获组替换内容.//命名捕获组只允许使用正则表达式匹配的一部分.var replaceContent = Regex.Replace(fileContent, @"page: (?[0-9]+)", match => $"page: {int.Parse(match.Groups["number"].值) + 1}");//将替换的内容写回文件.File.WriteAllText(文件路径,替换内容);}}
我还冒昧地将您的正则表达式更改为下面的那个.
page: (?[0-9]+)page: 与page:"字面匹配.(? 是一个名为 number 的命名捕获组的开始.然后我们可以在替换期间使用这个组.[0-9]+ 匹配 0 到 9 之间的数字一到无限次.这比使用 \d 更具体,因为 \d 也匹配其他数字字符.+ 使它比数字更匹配,允许数字 10 及以后的数字.) 是命名捕获组的结尾.
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?
解决方案
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.
这篇关于查找数字并替换 + 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文