正则表达式在数学运算中匹配和替换运算符

Ash*_*h M 5 c# regex regex-group

给定一个输入字符串

12/3
12*3/12
(12*54)/(3/4)
Run Code Online (Sandbox Code Playgroud)

我需要使用包含运算符的字符串查找并替换每个运算符

some12text/some3text
some12text*some2text/some12text
(some12text*some54text)/(some3text/some4text)
Run Code Online (Sandbox Code Playgroud)

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

34*157
Run Code Online (Sandbox Code Playgroud)

我需要翻译成:

document.getElementById("34").value*document.getElementById("157").value
Run Code Online (Sandbox Code Playgroud)

并返回到可以在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
}
Run Code Online (Sandbox Code Playgroud)

警告:我不能在foreach循环中进行毯子input.Replace(),因为它可能会错误地替换(12/123) - 它应该只匹配前12个替换

注意2:我可以使用string.Remove和string.Insert,但是在第一次匹配后会改变字符串,所以它会抛弃下一个匹配的计算

任何指针赞赏

fub*_*ubo 2

干得好

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

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

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

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