简体   繁体   English

替换C#中的模式值

[英]Replace pattern values in c#

i am having string "Test uid=1 Test2 uid=2 Test3 uid=3" 我有字符串“ Test uid = 1 Test2 uid = 2 Test3 uid = 3”

i wrote regex to get all uid. 我写了正则表达式来获取所有的uid。

That gives me list of uid {1,2,3} 这给了我uid {1,2,3}的列表

for this values i have some diff values {1 = 2015, 2=2016, 3=3014} 对于这个值,我有一些差异值{1 = 2015,2 = 2016,3 = 3014}

I tried to use Regex.replace(str, regexPattern, "") 我尝试使用Regex.replace(str,regexPattern,“”)

As it replace all the regex matching item by single value. 因为它将所有正则表达式匹配项替换为单个值。

Now i want to replace this old values by new value. 现在,我想用新值替换旧值。

Code

string str = "Test uid=1 Test2 uid=2 Test3 uid=3"
var uiList = regex.Matches(str);

I am thinking about MatchCollection. 我在考虑MatchCollection。

You can use the version of Regex.Replace accepting MatchEvaluator - Regex.Replace Method (String, String, MatchEvaluator) 您可以使用Regex.Replace接受MatchEvaluator的版本-Regex.Replace 方法(字符串,字符串,MatchEvaluator)

Sample method (without checking of input data): 样本方法(不检查输入数据):

string input = "Test uid=1 Test2 uid=2 Test3 uid=3";
var replacements = new Dictionary<string,string> {
    { "1", "2015" },
    { "2", "2016" },
    { "3", "3014" }
};
string output = Regex.Replace(input, @"(?<=uid=)\d+", m => replacements[m.Value]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM