首页 > 解决方案 > 在字符串中查找整数值并在处理后替换它们

问题描述

我有一个带有整数值的长字符串。我想用 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 并替换找到的整数。

标签: c#regexregex-group

解决方案


使用匹配评估器:

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.

推荐阅读