[英]How to replace a string a particular position with a matched Regular expression pattern at that position
所以,我有這個基本程序,它匹配字符串中的特定模式,然后將所有匹配項存儲在一個數組中。 然后我將每個匹配的元素附加到一個字符串中。
現在我的問題是,如何將原始字符串中匹配的模式替換為我根據regex
生成的修改后的字符串。
可以在此處找到示例工作程序: https : //dotnetfiddle.net/UvgOVc
如您所見,生成的最終字符串僅包含最后修改的字符串。 如何在替換中替換相應的匹配項?
代碼:
using System;
using System.Text.RegularExpressions;
using System.Linq;
public class Program
{
public static void Main()
{
string url = "Please ab123456 this is and also bc789456 and also de456789 ";
string[] queryString = getMatch(url,@"\w{2}\d{6}");
string[] formatted=new string[10000];
string finalurl=string.Empty;
for(int i=0;i<queryString.Length;i++)
{
formatted[i]="replace "+queryString[i];
Console.WriteLine(formatted[i]+"\n");
finalurl=Regex.Replace(url,@"\w{2}\d{6}",formatted[i]);
}
Console.WriteLine(finalurl);
}
private static string[] getMatch(string text, string expr)
{
string matched=string.Empty;
string[] matches=new string[100];
var mc = Regex.Matches(text, expr);
if ( text != string.Empty && mc.Count > 0)
{
matches = mc.OfType<Match>()
.Select(x => x.Value)
.ToArray();
}
return matches;
}
}
輸出:
replace ab123456
replace bc789456
replace de456789
Please replace de456789 this is and also replace de456789 and also replace de456789
您的代碼可以簡化為
string url = "Please ab123456 this is and also bc789456 and also de456789 ";
string[] queryString = Regex.Matches(url,@"\w{2}\d{6}").Cast<Match>().Select(x => x.Value).ToArray();
string finalurl=Regex.Replace(url,@"\w{2}\d{6}", "replace $&");
Console.WriteLine(finalurl); // => Please replace ab123456 this is and also replace bc789456 and also replace de456789
請參閱在線 C# 演示。
在這里, Regex.Matches(url,@"\\w{2}\\d{6}").Cast<Match>().Select(x => x.Value).ToArray()
將所有匹配項收集到queryString
變量中(如果您需要匹配值數組)。
Regex.Replace(url,@"\\w{2}\\d{6}", "replace $&")
查找后跟六位數字的兩個單詞字符的所有匹配項,並在匹配的文本之前附加replace
+ 空格(注意$&
是對整個匹配值的反向引用)。
如果您計划對找到的匹配進行更多操作,請考慮使用匹配評估器。 說,你在某處定義了SomeMethod(string s)
,然后你可以使用
string finalurl=Regex.Replace(url,@"\w{2}\d{6}", m =>
SomeMethod(m.Value);
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.