-3

I want to replace all instances of substrings that match a regular expression with another string in C#. For example, the function call could look something like this:

inputString.Replace("foo*bar", "baz");

If the input string was (example only):

"foo2bar and foo2bax and fooTheQuickFax"

The output would be (example only):

"baz and foo2bax and fooTheQuickFax"

Does anyone know how to achieve this outcome?

Note: This question is NOT a duplicate. This is asking about Regex specifically, featuring an example. It is not asking about how to find the string between two strings - the person who marked this as duplicate did not read the question.

A X
  • 905
  • 2
  • 13
  • 31

2 Answers2

3
Regex.Replace("foo2bar and foo2bax and fooTheQuickFax", "foo.*bar", "baz");
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
0

Use Regex.Replace() method like

  string pattern = "\\foo?bar";
  string replacement = "baz";
  Regex rgx = new Regex(pattern);
  string result = rgx.Replace(input, replacement);
Rahul
  • 76,197
  • 13
  • 71
  • 125