Extract String between 2 dollar sign

  • A+
Category:Languages

I have string which contains a variable. But i need to replace the name with what i have in the db.

string text = "hello $$name$$, good morning"

How can i extract the name by using Regex?

This only works if i have single $

var MathedContent = Regex.Match((string)bodyObject, @"/$.*?/$");

 


You could define regular expression, "(/$/$)(.*?)(/$/$)" with 3 different groups:

 "(/$/$)(.*?)(/$/$)"  ^^^^^^|^^^^^|^^^^^^     $1    $2    $3 

and then if you need just simple replacement you can do something like this:

string replacedText = Regex     .Replace("hello $$name$$, good morning", @"(/$/$)(.*?)(/$/$)", "replacement"); //hello replacement, good morning 

or combine with the other groups

string replacedText = Regex     .Replace("hello $$name$$, good morning", @"(/$/$)(.*?)(/$/$)", "$1replacement$3"); //hello $$replacement$$, good morning 

On the other hand, if you need more control you could do something like this(tnx to Wiktor):

IDictionary<string, string> factory = new Dictionary<string, string> {     {"name", "replacement"} };  string replacedText = Regex.Replace(     "hello $$name$$, good morning",     @"(?<b>/$/$)(?<replacable>.*?)(?<e>/$/$)",     m => m.Groups["b"].Value + factory[m.Groups["replacable"].Value] + m.Groups["e"].Value); //hello $$replacement$$, good morning 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: