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
Your question is slightly ambigous as to whether you want to replace the entire $$name$$
or find the string between the dollars.
Here's working code for both:
Replace $$name$$ with Bob
string input = "hello $$name$$, good morning";
var replaced = Regex.Replace(input, @"(\$\$\w+\$\$)", "Bob");
Console.WriteLine($"replaced: {replaced}");
Prints replaced: hello Bob, good morning
Extract name from string:
string input = "hello $$name$$, good morning";
var match = Regex.Match(input, @"\$\$(\w+)\$\$").Groups[1].ToString();
Console.WriteLine($"match: {match}");
Prints match: name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With