简体   繁体   English

C#正则表达式-匹配特定的字符串,后跟一个substring1或substring2

[英]C# Regex - Match specific string followed by a substring1 or substring2

Input : This AbT5xY\\nAppleUvW is a test AbT5xY AppleUvW is a test and AbT5xrAppleUvW and another AbT5xY\\nmangoUvW test 输入This AbT5xY\\nAppleUvW is a test AbT5xY AppleUvW is a test and AbT5xrAppleUvW and another AbT5xY\\nmangoUvW test

Following RegEx gives the output: This SomeFruitUvW is a test SomeFruitUvW is a test and AbT5xrAppleUvW and another SomeFruitUvW 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");

But what I need is that if AbT5xY is followed by Apple then replace AbT5xYApple with Fruit1 ; 但我需要的是,如果AbT5xY其次是Apple然后更换AbT5xYAppleFruit1 ; and if AbT5xY is followed by mango replace AbT5xYmango with Fruit2 . 如果AbT5xY之后是mango AbT5xYmangoFruit2替换Fruit2 Hence, 因此,

Desired output : This Fruit1UvW is a test Fruit1UvW is a test and AbT5xrAppleUvW and another Fruit2UvW test. 所需的输出This Fruit1UvW is a test Fruit1UvW is a test and AbT5xrAppleUvW and another Fruit2UvW test.

Note : 注意事项

  1. I'm ignoring whitespace characters (newline, blanks, tabs etc.) between AbT5xY and Apple or AbT5xY and mango. 我忽略了AbT5xY和Apple或AbT5xY和芒果之间的空白字符(换行符,空格,制表符等)。 Also AbT5xrAppleUvW is correctly not matched since it has AbT5xr and not AbT5xY before Apple. 此外AbT5xrAppleUvW正确不匹配,因为它有AbT5xr而不是AbT5xY苹果之前。
  2. I think C#'s RegEx has something called substitutions, groups, captures that need to be used here but I'm struggling with how to use these here. 我认为C#的RegEx有一些需要在这里使用的替代项,组,捕获,但是我在为如何在此处使用而苦苦挣扎。

You may capture the Apple and mango into Group 1 and when replacing, use a match evaluator, where you can check the Group 1 value, and then perform the necessary replacement based on the check result: 您可以将Applemango捕获到第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

See the C# demo . 参见C#演示

The AbT5xY\\s*(Apple|mango) regex matches AbT5xY , then 0+ whitespaces (note a single backslash as I used a verbatim string literal) and then matches and captures either Apple or mango into Group 1. The m.Groups[1].Value == "Apple" if Group 1 value is Apple , and then proceeds to replace the match. AbT5xY\\s*(Apple|mango)正则表达式匹配AbT5xY ,然后匹配0+空格(当我使用逐字字符串文字时,请注意一个反斜杠),然后匹配并将Applemango捕获到组1中m.Groups[1].Value == "Apple"如果组1的值为Apple ,然后继续替换匹配项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM