c# - 在字符串中查找整数值并在处理后替换它们
问题描述
我有一个带有整数值的长字符串。我想用 Regex.Replace 找到整数值,并在与变量相乘后替换它们。
类似于以下内容
string text = "The the quick brown fox 23jumps o65ver th66e lazy dog.";
将会
The the quick brown fox VAL*23jumps oVAL*65ver thVAL*66e lazy dog.
我使用了Regex.Replace(text, @"(\d+)", @"$1");
. 但是,这不能处理 $1 并替换找到的整数。
解决方案
使用匹配评估器:
Regex.Replace(text, @"\d+", m => $"{VAL * int.Parse(m.Value)}")
请参阅C# 演示:
var text = "The the quick brown fox 23jumps o65ver th66e lazy dog.";
var VAL = 4;
Console.WriteLine(Regex.Replace(text, @"\d+", m => $"{VAL * int.Parse(m.Value)}"));
// => The the quick brown fox 92jumps o260ver th264e lazy dog.
推荐阅读
- windows - 使用 WinDBG 和 VMware 进行离线内核模式驱动程序调试 - 我缺少哪些符号文件?
- java - 我正在使用 Libgdx 构建手机游戏。有人可以告诉我如何将屏幕设置为一种尺寸吗?
- python - 从远程PowerShell运行时Python权限被拒绝
- sql - 获取SQL中计数列的总和
- python - 确保测验不会两次询问相同的问题
- php - 如何在 Laravel 中存储数组?
- dart - 在 null 上调用了 getter 'storeNumber'(接收方:null)
- arrays - 如何将两个(或更多)tableViewCells 添加在一起以形成“总数”
- java - 如何在编译时未知的索引处从局部变量加载引用?
- ajax - 为什么我在 ajax 调用中更改数据时会出错