Regex matches and replaces operators in a mathematical operation

Given the input string

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

I need to find and replace each operator with a string containing the operator

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

practical application: From the backend (C #) I have the following line

34*157

which I need to translate to:

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

and returns to the screen, which can be launched in the eval () function.

I still 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 make an empty entry. Replace () in the foreach loop, as it may incorrectly replace (12/123) - it should only match the first 12 to replace

Caution2: I can use string.Remove and string.Insert, but this mutates the string after the first match, so it discards the calculation of the next match

Any pointers appreciated

+4
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"); 

Fiddle: https://dotnetfiddle.net/JUknx2

+2

Source: https://habr.com/ru/post/1675905/


All Articles