我有以下字符串。
"hello [#NAME#]. nice to meet you. I heard about you via [#SOURCE#]."
在上面的文本中,我有两个占位符。名称和来源
我想使用 Reg Ex 提取这些子字符串。
查找这些占位符列表的正则表达式模式是什么。
我试过了
string pattern = @"\[#(\w+)#\]";
结果
hello
NAME
. nice to meet you. I heard about you via
SOURCE
.
我想要的只是
NAME
SOURCE
示例代码
string tex = "hello [#NAME#]. nice to meet you. I heard about you via [#SOURCE#].";
string pattern = @"\[#(\w+)#\]";
var sp = Regex.Split(tex, pattern);
sp.Dump();
最佳答案
您的正则表达式工作正常。就是这样 Regex.Split()
应该行为(见 the doc )。如果你说的真的是你想要的,你可以使用类似的东西:
var matches = from Match match in Regex.Matches(text, pattern)
select match.Groups[1].Value;
另一方面,如果您想使用某些规则替换占位符(例如使用 Dictionary<string, string>
),那么您可以这样做:
Regex.Replace(text, pattern, m => substitutions[m.Groups[1].Value]);
关于时间:2019-03-08 标签:c#正则表达式: find placeholders as substring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6238769/