[英]Find-Replace pattern in C#
我有一個復雜的情況,我需要解析一個很長的字符串。 我必須在字符串中查找一個模式,然后將其替換為另一個模式。 我知道我可以簡單地使用find/replace
方法,但情況略有不同。
我有一個包含以下模式的字符串
#EPB_IMG#index-1_1.jpg#EPB_IMG
#EPB_IMG#index-1_2.jpg#EPB_IMG
#EPB_IMG#index-1_3.jpg#EPB_IMG
#EPB_IMG#index-1_4.jpg#EPB_IMG
我希望它格式化為
#EPB_IMG#index-1_1.jpg|index-1_2.jpg|index-1_3.jpg|index-1_4.jpg#EPB_IMG
我對Regex
和尋求幫助的了解不多。
正則表達式過大了:
var parts = s.Split(new string[] { "#EPB_IMG", "#", "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries);
var result = string.Join("|", parts);
Console.WriteLine("#EPB_IMG#" + result + "#EPB_IMG"); // prints your result.
也許是這樣的:
表達式: \\w+#(?<Image>(.+)\\.jpg)#\\w+
替換: ${Image}
結果: string.Format("#EPB_IMG#{0}#EPB_IMG", string.Join("|", listOfMatches))
注意:正則表達式使用以下資源進行了測試: http : //regexhero.net/tester/
結果未經測試,但應該可以!
var result = "#EPB_IMG" + Regex.Matches(inputString, @"#EPB_IMG(.+)#EPB_IMG")
.Cast<Match>()
.Select(m => m.Groups[1].Value)
.Aggregate((f, f2) => f + "|" + f2) + "#EPB_IMG";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.