【问题标题】:Finding integer values in a string and replace them after processing在字符串中查找整数值并在处理后替换它们
【发布时间】:2018-10-05 18:39:25
【问题描述】:

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

【问题讨论】:

  • \d 将仅匹配 1 位数字。你需要\d+
  • @RuiJarimba 抱歉那是 \d+
  • @WiktorStribiżew VAL 这里是一个整数值,我想在评估后使用它。
  • @PoulBak 该表单不评估 VAL*$1

标签: c# regex regex-group


【解决方案1】:

使用匹配评估器:

Regex.Replace(text, @"\d+", m => $"{VAL * int.Parse(m.Value)}")

C# demo

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.

【讨论】:

    猜你喜欢
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    • 2014-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    相关资源
    最近更新 更多