我需要替换以%
开头的单词。
例如Welcome to home | %brand %productName
希望分开以%
开头的单词,这会给我{ brand, productName }
。
我的正则表达式低于平均水平,所以希望得到帮助。
答案 0 :(得分:2)
以下代码可能会对您有所帮助:
string[] splits = "Welcome to home | %brand %productName".Split(' ');
List<string> lstdata = new List<string>();
for(i=0;i<splits.length;i++)
{
if(splits[i].StartsWith("%"))
lstdata.Add(splits[i].Replace('%',''));
}
答案 1 :(得分:1)
string.split方法没有错,请注意,但这是一个正则表达式方法:
string input = @"Welcome to home | %brand %productName";
string pattern = @"%\S+";
var matches = Regex.Matches(input, pattern);
string result = string.Empty;
for (int i = 0; i < matches.Count; i++)
{
result += "match " + i + ",value:" + matches[i].Value + "\n";
}
Console.WriteLine(result);
答案 2 :(得分:0)
试试这个:
(?<=%)\w+
这会查找紧跟在百分号后面的任何单词字符组合。
现在,如果您正在搜索并替换这些匹配项,那么您可能也想要删除%符号,因此您需要删除lookbehind组并且只需要:
%\w+
但是这样做,您的替换代码需要修剪每个匹配的%符号才能自行获取单词。