Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 提取2美元符号之间的字符串_C#_.net_Regex - Fatal编程技术网

C# 提取2美元符号之间的字符串

C# 提取2美元符号之间的字符串,c#,.net,regex,C#,.net,Regex,我有一个包含变量的字符串。但是我需要用数据库中的内容替换名称 string text=“你好$$name$$,早上好” 如何使用Regex提取名称 仅当我有单个$ var MathedContent=Regex.Match((字符串)bodyObject,@“\$.*?\$”您可以定义正则表达式,“(\$\$)(.*?)(\$\$)”包含3个不同的组: "(\$\$)(.*?)(\$\$)" ^^^^^^|^^^^^|^^^^^^ $1 $2 $3 然后,如果您只需要简

我有一个包含变量的字符串。但是我需要用数据库中的内容替换
名称

string text=“你好$$name$$,早上好”

如何使用
Regex
提取
名称

仅当我有单个
$


var MathedContent=Regex.Match((字符串)bodyObject,@“\$.*?\$”

您可以定义正则表达式,
“(\$\$)(.*?)(\$\$)”
包含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-to):

IDictionary工厂=新字典
{
{“名称”、“替换”}
};
string replacedText=Regex.Replace(
“你好$$name$$,早上好”,
@"(?\$\$)(?.*?)(?\$\$)",
m=>m.Groups[“b”].Value+工厂[m.Groups[“replacable”].Value]+m.Groups[“e”].Value);
//你好$$更换$$,早上好

您的问题有点模棱两可,您想替换整个
$$name$$
还是查找美元之间的字符串

以下是这两个方面的工作代码:

用Bob替换$$name$$

string input=“你好$$name$$,早上好”;
var replaced=Regex.Replace(输入@“(\$\$\w+\$\$)”,“Bob”);
WriteLine($“替换:{replaced}”);
打印
已替换:你好,鲍勃,早上好

从字符串中提取名称:

string input=“你好$$name$$,早上好”;
var match=Regex.match(输入,@“\$\$(\w+)\$\$”).Groups[1].ToString();
WriteLine($“匹配:{match}”);

打印
match:name

如果要捕获
$$
分隔符之间的文本,但排除
$
本身,则可以使用:
(?使用否定集,
[^]
。例如
[^$]+
,我们将在其中匹配到下一个
$

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

Regex.Replace(text, @"\$\$[^$]+\$\$", "Jabberwocky");
结果:

 hello Jabberwocky, good morning
name


更多的冗长但更容易阅读而不逃逸,模式>代码[$] [^ $] [$] } /代码> .< /p>该语言是什么?<代码>/\$$([^ $ ])\ $ \ /< /代码>应该与C语言匹配。如果你打算使用<代码>名称<代码>来获取其他地方的值,你可以考虑<代码>正则表达式。替换((string)BODYObjor,@ \ \ \ $ \(\W+)\ $ \ $”,M= >DCT。[m.Groups[1].Value])

,但您需要准备一个带有所有可能键的
dct
字典。您需要替换整个
$$name$$
还是只替换
name
并保留
$$$
?我想您也可以使用两个捕获组
(\$\$).*(\$\$\$\$code>)并在替换中使用
$1replacement$2
string input = "hello $$name$$, good morning";
Regex rx = new Regex(@"(?<=\$\$)(.*?)(?=\$\$)");

Console.WriteLine(rx.Match(input).Groups[1].Value); 
string input = "hello $$name$$, good morning";
Regex rx = new Regex(@"(?<=\$\$)(.*?)(?=\$\$)");

Console.WriteLine(rx.Match(input).Groups[1].Value); 
name