[英]Find-Replace pattern in C#
I have a complex situation where I need to parse a very long string. 我有一个复杂的情况,我需要解析一个很长的字符串。 I have to look for a pattern in the string and replace that pattern with another.
我必须在字符串中查找一个模式,然后将其替换为另一个模式。 I know I can simply use
find/replace
method but my case is bit different. 我知道我可以简单地使用
find/replace
方法,但情况略有不同。
I have a string that contains the following pattern 我有一个包含以下模式的字符串
#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
and I want it to format as 我希望它格式化为
#EPB_IMG#index-1_1.jpg|index-1_2.jpg|index-1_3.jpg|index-1_4.jpg#EPB_IMG
I don't know much about Regex
and seeking for help. 我对
Regex
和寻求帮助的了解不多。
Regex is overkill: 正则表达式过大了:
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.
Maybe something like this: 也许是这样的:
Expression: \\w+#(?<Image>(.+)\\.jpg)#\\w+
表达式:
\\w+#(?<Image>(.+)\\.jpg)#\\w+
Replacement: ${Image}
替换:
${Image}
Result: string.Format("#EPB_IMG#{0}#EPB_IMG", string.Join("|", listOfMatches))
结果:
string.Format("#EPB_IMG#{0}#EPB_IMG", string.Join("|", listOfMatches))
NOTE: Regex tested with: http://regexhero.net/tester/ 注意:正则表达式使用以下资源进行了测试: http : //regexhero.net/tester/
Result is untested, but should work! 结果未经测试,但应该可以!
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.