我有一个包含变量的字符串。但是我需要用数据库中的内容替换name
。
string text = "hello $$name$$, good morning"
如何使用name
提取Regex
?
这仅在我有一个$
var MathedContent = Regex.Match((string)bodyObject, @"\$.*?\$");
答案 0 :(得分:3)
您可以使用3个不同的组来定义正则表达式"(\$\$)(.*?)(\$\$)"
:
"(\$\$)(.*?)(\$\$)"
^^^^^^|^^^^^|^^^^^^
$1 $2 $3
,然后,如果您只需要简单更换,则可以执行以下操作:
string replacedText = Regex
.Replace("hello $$name$$, good morning", @"(\$\$)(.*?)(\$\$)", "replacement");
//hello replacement, good morning
或与其他团体合并
string replacedText = Regex
.Replace("hello $$name$$, good morning", @"(\$\$)(.*?)(\$\$)", "$1replacement$3");
//hello $$replacement$$, good morning
另一方面,如果您需要更多控制权,则可以执行以下操作(tnx至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
答案 1 :(得分:3)
关于您要替换整个$$name$$
还是要找到美元之间的字符串,您的问题有点模棱两可。
这是这两个的工作代码:
用鲍勃代替$$ name $$
string input = "hello $$name$$, good morning";
var replaced = Regex.Replace(input, @"(\$\$\w+\$\$)", "Bob");
Console.WriteLine($"replaced: {replaced}");
打印replaced: hello Bob, good morning
从字符串中提取名称:
string input = "hello $$name$$, good morning";
var match = Regex.Match(input, @"\$\$(\w+)\$\$").Groups[1].ToString();
Console.WriteLine($"match: {match}");
打印match: name
答案 2 :(得分:3)
如果要捕获$$
分隔符之间的文本,但不包括$$
本身,则可以使用lookaround:(?<=\$\$).*?(?=\$\$)
解决方法是零长度的断言(很像\b
),它与字符匹配,但不将它们包括在结果中。 (?<=XXX)YYY
与YYY
匹配,前提是XXX
在之前。同样,YYY(?=ZZZ)
与YYY
匹配,条件是之后 ZZZ
。
var match = Regex.Match("hello $$name$$, good morning", @"(?<=\$\$).*?(?=\$\$)");
Console.WriteLine(match.Value); // outputs "name"
答案 3 :(得分:1)
string input = "hello $$name$$, good morning";
Regex rx = new Regex(@"(?<=\$\$)(.*?)(?=\$\$)");
Console.WriteLine(rx.Match(input).Groups[1].Value);
结果:
name
答案 4 :(得分:0)
使用否定集[^ ]
。例如[^$]+
,我们将匹配到下一个$
。
string text = "hello $$name$$, good morning";
Regex.Replace(text, @"\$\$[^$]+\$\$", "Jabberwocky");
结果:
hello Jabberwocky, good morning
模式[$]{2}[^$]+[$]{2}
更冗长,但更易于阅读而又不逃脱。