[英]Csharp: Find & Replace string match between specific characters || in a string using Regex
I have a string like:我有一个像这样的字符串:
string originalStringBefore = "http://www.abc.com?a=||ThisIsForRndNumber||&qq=hello&jj=||ThisIsForRndNumberAlso||";
I want every string which comes between ||我想要介于 || 之间的每个字符串to be replaced with a random number.
替换为随机数。
Now, the random number generation is easy, but i can't find the way to write a Regular expression to search the string using a pattern and replace it.现在,随机数生成很容易,但我找不到编写正则表达式以使用模式搜索字符串并替换它的方法。
I don't want to do it by string manipulation functions.我不想通过字符串操作函数来做到这一点。
Expected Solution/ outcome:预期的解决方案/结果:
string originalStringAfter = "http://www.abc.com?a=||254877787||&qq=hello&jj=||6594741454||";
It looks like you want this regex:看起来你想要这个正则表达式:
(?<=\|\|)\w+(?=\|\|)
which finds alphanumeric between ||
查找
||
之间的字母数字and leaves strings that contain non-alphanumeric characters (like &
) alone.并单独留下包含非字母数字字符(如
&
)的字符串。
Then, in C#:然后,在 C# 中:
public String ComputeReplacement(Match m) {
return RandomNumberString();
}
resultString = Regex.Replace(subjectString, @"(?<=\|\|)\w+(?=\|\|)", new MatchEvaluator(ComputeReplacement));
string originalStringBefore = "http://www.abc.com?a=||ThisIsForRndNumber||&qq=hello&jj=||ThisIsForRndNumberAlso||";
Random r = new Random();
Regex rgx = new Regex(@"\|\|.*?\|\|");
Console.WriteLine(rgx.Replace(originalStringBefore, "||" + r.Next(int.MaxValue) + "||"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.