[英]Regex replace with separate replacement depending on the match
假设我有一个字典( 单词及其替换):
var replacements = new Dictionary<string,string>();
replacements.Add("str", "string0");
replacements.Add("str1", "string1");
replacements.Add("str2", "string2");
...
和输入字符串:
string input = @"@str is a #str is a [str1] is a &str1 @str2 one test $str2 also [str]";
编辑 :
预期产量:
string0 is a string0 is string0 is string1 string2 one test string2
我想用字典中相应的条目/值替换' [CharSymbol] word '的所有出现。
Charsymbol可以是@#$%^&* [] ..以及单词有效后的']',即[str]。
我尝试了以下替换
string input = @"@str is a #str is a [str1] is a &str1 @str2 one test $str2 also [str]";
string pattern = @"(([@$&#\[]+)([a-zA-Z])*(\])*)"; // correct?
Regex re = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
// string outputString = re.Replace(input,"string0");
string newString = re.Replace(input, match =>
{
Debug.WriteLine(match.ToString()); // match is [str] #str
string lookup = "~"; // default value
replacements.TryGetValue(match.Value,out lookup);
return lookup;
});
我如何得到str,str1等比赛,即没有charsymbol的单词。
这适合吗?
(?<=[#@&$])(\w+)|[[\w+]]
它与您的示例中的以下内容匹配:
@ str
是# str
是[ str
]是一个& str1
@ str2
一个测试$ str2
试试这个正则Regex
: ([@$&#\\[])[a-zA-Z]*(\\])?
,并用string0
替换
你的代码应该是这样的:
var replacements = new Dictionary<string, string>
{
{"str", "string0"},
{"str1", "string1"},
{"str2", "string2"}
};
String input="@str is a #str is a [str] is a &str @str can be done $str is @str";
foreach (var replacement in replacements)
{
string pattern = String.Format(@"([@$&#\[]){0}(\])?", replacement.Key);
var re = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
string output = re.Replace(input,
String.Format("{0}", replacement.Value));
}
将你的正则表达式改为:
// Move the * inside the brackets around [a-zA-Z]
// Change [a-zA-Z] to \w, to include digits.
string pattern = @"(([@$&#\[]+)(\w*)(\])*)";
改变这一行:
replacements.TryGetValue(match.Value,out lookup);
对此:
replacements.TryGetValue(match.Groups[3].Value,out lookup);
注意:您的IgnoreCase
不是必需的,因为您在正则表达式中匹配大写和小写。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.