RegEx to replace the first and last character of string for a particular match

Something like this.

The sentence is

string ttt = "This is ?chef? and ?teacher? time";

This sentence should change to

ttt = "This is 'chef' and 'teacher' time";

I was looking at some online samples Regex.Replace(ttt, @"\?([^\$]*)\?", "REPLACE"); but I am not able to figure out what should I write in place of REPLACE . It should be per word basis.

Kindly help me with this.

Upvotes: 1

Views: 1408

Answers (1)

hwnd
hwnd

Reputation: 70732

You would reference the capture group inside the replacement call. It's called a back-reference.

String ttt = "This is ?chef? and ?teacher? time";
String result = Regex.Replace(ttt, @"\?([^?]*)\?", "'$1'");
Console.WriteLine(result); //=> "This is 'chef' and 'teacher' time"

Back-references recall what was matched by a capture group ( ... ). A backreference is specified as ($); followed by a digit indicating the number of the group to be recalled.

Note: I used [^?] for the negation instead of matching everything except a literal $ here.


But if you're just wanting to replace ?, a simple replacement would suffice:

String result = ttt.Replace("?", "'");

Upvotes: 2

Related Questions