【问题标题】:Regex match and replace operators in math operation正则表达式匹配和替换数学运算中的运算符
【发布时间】:2017-09-26 12:05:42
【问题描述】:

给定一个输入字符串

12/3
12*3/12
(12*54)/(3/4)

我需要查找每个运算符并将其替换为包含运算符的字符串

some12text/some3text
some12text*some2text/some12text
(some12text*some54text)/(some3text/some4text)

实际应用: 从后端(c#),我有以下字符串

34*157

我需要翻译成:

document.getElementById("34").value*document.getElementById("157").value

并返回到可以在 eval() 函数中运行的屏幕。

目前为止

var pattern = @"\d+";
var input = "12/3;

Regex r = new Regex(pattern);
var matches = r.Matches(input);

foreach (Match match in matches)
{
 // im at a loss what to match and replace here
}

注意:我不能在 foreach 循环中执行一揽子 input.Replace(),因为它可能会错误地替换 (12/123) - 它应该只匹配要替换的前 12 个

Caution2:我可以使用 string.Remove 和 string.Insert,但这会在第一个匹配后改变字符串,所以它会抛出下一个匹配的计算

欢迎指点

【问题讨论】:

标签: c# regex regex-group


【解决方案1】:

给你

string pattern = @"\d+"; //machtes 1-n consecutive digits
var input = "(12*54)/(3/4)";
string result = Regex.Replace(input, pattern, "some$0Text"); 

$0 是匹配模式\d+ 的字符组。你也可以写

string result = Regex.Replace(input, pattern, m => "some"+ m.Groups[0]+ "Text"); 

小提琴:https://dotnetfiddle.net/JUknx2

【讨论】:

  • 太棒了 - 喜欢简单!
猜你喜欢
  • 1970-01-01
  • 2014-05-06
  • 2013-11-18
  • 2015-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多