[英]C# Regex - Match specific string followed by a substring1 or substring2
输入 : This AbT5xY\\nAppleUvW is a test AbT5xY AppleUvW is a test and AbT5xrAppleUvW and another AbT5xY\\nmangoUvW test
遵循RegEx的输出: This SomeFruitUvW is a test SomeFruitUvW is a test and AbT5xrAppleUvW and another SomeFruitUvW test.
Regex.Replace(st, "AbT5xY\\s*(Apple)|(mango)", "SomeFruit");
但我需要的是,如果AbT5xY
其次是Apple
然后更换AbT5xYApple
与Fruit1
; 如果AbT5xY
之后是mango
AbT5xYmango
用Fruit2
替换Fruit2
。 因此,
所需的输出 : This Fruit1UvW is a test Fruit1UvW is a test and AbT5xrAppleUvW and another Fruit2UvW test.
注意事项 :
AbT5xY
和Apple或AbT5xY
和芒果之间的空白字符(换行符,空格,制表符等)。 此外AbT5xrAppleUvW
正确不匹配,因为它有AbT5xr
而不是AbT5xY
苹果之前。 您可以将Apple
和mango
捕获到第1组中,并在进行替换时使用匹配评估器,您可以在其中检查第1组的值,然后根据检查结果执行必要的替换:
var pat = @"AbT5xY\s*(Apple|mango)";
var s = "This AbT5xY\nAppleUvW is a test AbT5xY AppleUvW is a test and AbT5xrAppleUvW and another AbT5xY\nmangoUvW test";
var res = Regex.Replace(s, pat, m =>
m.Groups[1].Value == "Apple" ? "Fruit1" : "Fruit2");
Console.WriteLine(res);
// => This Fruit1UvW is a test Fruit1UvW is a test and AbT5xrAppleUvW and another Fruit2UvW test
参见C#演示 。
AbT5xY\\s*(Apple|mango)
正则表达式匹配AbT5xY
,然后匹配0+空格(当我使用逐字字符串文字时,请注意一个反斜杠),然后匹配并将Apple
或mango
捕获到组1中m.Groups[1].Value == "Apple"
如果组1的值为Apple
,然后继续替换匹配项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.