【问题标题】:C# Regex - Match specific string followed by a substring1 or substring2C# Regex - 匹配特定字符串,后跟 substring1 或 substring2
【发布时间】:2017-08-09 05:47:04
【问题描述】:

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

按照正则表达式给出输出: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。因此,

所需输出This Fruit1UvW is a test Fruit1UvW is a test and AbT5xrAppleUvW and another Fruit2UvW test.

注意

  1. 我忽略了 AbT5xY 和 Apple 或 AbT5xY 和 mango 之间的空白字符(换行符、空格、制表符等)。 AbT5xrAppleUvW 也没有正确匹配,因为它在 Apple 之前有 AbT5xr 而不是 AbT5xY
  2. 我认为 C# 的 RegEx 有一些称为替换、组、捕获的东西,需要在这里使用,但我正在努力解决如何在这里使用这些内容。

【问题讨论】:

  • 只需执行 2 个正则表达式并替换 2 次。我认为你不能以任何其他方式做到这一点
  • 只需尝试使用 Replace(string input, string pattern, MatchEvaluator evaluator) 的覆盖,您的自定义 MatchEvaluator 将为您提供匹配字符串值所需的正确值
  • @JakubDąbek 我刚刚添加了注释 2。

标签: c# regex


【解决方案1】:

您可以将Applemango捕获到Group 1中,替换时使用匹配评估器,您可以在其中检查Group 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# demo

AbT5xY\s*(Apple|mango) 正则表达式匹配 AbT5xY,然后是 0+ 个空格(注意一个反斜杠,因为我使用了 verbatim 字符串文字),然后匹配并捕获 Applemango进入第 1 组。如果第 1 组的值为Apple,则为m.Groups[1].Value == "Apple",然后继续替换匹配项。

【讨论】:

  • 从您的解决方案中,我还学习了如何将 LINQ 用于匹配评估器 - 如果相应的评估不太复杂,这会很方便。
  • @nam 我在这里很挑剔,但这里没有 LINQ,而是一个 lambda 表达式。语义相当混乱,因为人们几乎主要在 LINQ 查询中看到 lambda。
  • @JakubDąbek 同意。 Linq 使用 Lambda 表达式来执行它的一些功能
猜你喜欢
  • 2018-07-24
  • 2010-11-22
  • 2023-02-13
  • 2023-02-01
  • 2019-03-14
  • 1970-01-01
  • 1970-01-01
  • 2015-03-23
  • 1970-01-01
相关资源
最近更新 更多