5

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

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.

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

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

Any pointers appreciated

Ash M
  • 1,399
  • 2
  • 10
  • 23
  • 1
    Really, is [`Regex.Replace(s, @"\d+", "document.getElementById(\"$&\").value")`](http://regexstorm.net/tester?p=%5cd%2b&i=12%2f3%0d%0a12*3%2f12%0d%0a%2812*54%29%2f%283%2f4%29&r=document.getElementById%28%22%24%26%22%29.value) that you need? Why use `Regex.Matches`? – Wiktor Stribiżew Apr 28 '17 at 11:27

1 Answers1

2

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+. You can also write

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

Fiddle: https://dotnetfiddle.net/JUknx2

fubo
  • 44,811
  • 17
  • 103
  • 137