简体   繁体   English

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

[英]Regex match and replace operators in math operation

Given an input string 给定一个输入字符串

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

I need to find and replace each operator with a string that contains the operator 我需要使用包含运算符的字符串查找并替换每个运算符

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

practical application: From a backend (c#), i have the following string 实际应用:从后端(c#),我有以下字符串

34*157

which i need to translate to: 我需要翻译成:

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

and returned to the screen which can be run in an eval() function. 并返回到可以在eval()函数中运行的屏幕。

So far I have 到目前为止我有

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
}

Caution: i cannot do a blanket input.Replace() in the foreach loop, as it may incorrectly replace (12/123) - it should only match the first 12 to replace 警告:我不能在foreach循环中进行毯子input.Replace(),因为它可能会错误地替换(12/123) - 它应该只匹配前12个替换

Caution2: I can use string.Remove and string.Insert, but that mutates the string after the first match, so it throws off the calculation of the next match 注意2:我可以使用string.Remove和string.Insert,但是在第一次匹配后改变字符串,所以它会抛弃下一个匹配的计算

Any pointers appreciated 任何指针赞赏

Here you go 干得好

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

$0 is the character group matching the pattern \\d+ . $0是与模式\\d+匹配的字符组。 You can also write 你也可以写

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM