【发布时间】: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.
注意:
- 我忽略了
AbT5xY和 Apple 或AbT5xY和 mango 之间的空白字符(换行符、空格、制表符等)。AbT5xrAppleUvW也没有正确匹配,因为它在 Apple 之前有AbT5xr而不是AbT5xY。 - 我认为 C# 的 RegEx 有一些称为替换、组、捕获的东西,需要在这里使用,但我正在努力解决如何在这里使用这些内容。
【问题讨论】:
-
只需执行 2 个正则表达式并替换 2 次。我认为你不能以任何其他方式做到这一点
-
只需尝试使用
Replace(string input, string pattern, MatchEvaluator evaluator)的覆盖,您的自定义MatchEvaluator将为您提供匹配字符串值所需的正确值 -
@JakubDąbek 我刚刚添加了注释 2。