Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract String between 2 dollar sign

Tags:

c#

.net

regex

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, @"\$.*?\$");

like image 587
BeautySandra Avatar asked Oct 16 '25 20:10

BeautySandra


2 Answers

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
like image 75
Johnny Avatar answered Oct 18 '25 11:10

Johnny


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

like image 30
Erresen Avatar answered Oct 18 '25 10:10

Erresen