简体   繁体   English

Regex.Replace:基于可选组的条件替换

[英]Regex.Replace: Conditional replacement based on optional group

I am using Regex.Replace in C#. 我在C#中使用Regex.Replace。 In the replaced string, I want to put a condition that part of the string only comes out if one of the optional group is captured. 在替换的字符串中,我想提出一个条件,即只有捕获了可选组之一时,字符串的一部分才会出现。 For example, I have this regex:- 例如,我有这个正则表达式:

(?<Expiry>\d+[my])\s+(?<Flag>[a-z][A-Z])?\s*$)

Note that Flag captured group is optional . 请注意,“ Flag捕获”组是可选的

The replacement string is 替换字符串是

"Expiry is ${Expiry}. Flag is : ${Flag}"

Now I want "Flag is : ${Flag}" string only appear in the result if the Flag group is captured. 现在,我希望仅在捕获到Flag组的情况下,字符串"Flag is : ${Flag}"才会出现在结果中。

I am using following code: 我正在使用以下代码:

var regex = new
Regex("(?<Expiry>\d+[my])\s+(?<Flag>[a-z][A-Z])?\s*$)",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
string result = regex.Replace("10y", "Expiry is ${Expiry}. Flag is : ${Flag}";

Result should by Expiry is 10y . 结果Expiry is 10yExpiry is 10y

string result = regex.Replace("10y abc", "Expiry is ${Expiry}. Flag is ${Flag}");

Result should be "Expiry is 10y. Flag is : abc". 结果应为“到期时间为10y。标志为:abc”。

Any help is much appreciated. 任何帮助深表感谢。

You may use different replacement values based on whether the specified group participated in the match (=matched) or not. 您可以根据指定的组是否参与匹配(= matched)来使用不同的替换值。

See the example below: 请参阅以下示例:

var s = "1m aZ";
var pat = @"(?<Expiry>\d+[my])\s+(?<Flag>[a-z][A-Z])?\s*$";
var res = Regex.Replace(s, pat, m => m.Groups["Flag"].Success ? 
    string.Format("Flag is : {0}.", m.Groups["Flag"].Value) : 
    string.Format("Expiry is {0}.", m.Groups["Expiry"].Value));
Console.WriteLine(res);

See the online demo 观看在线演示

If Flag group matches, the replacement will be string.Format("Flag is : {0}.", m.Groups["Flag"].Value) , else, the replacement will only contain the expiry message. 如果Flag组匹配,则替换将为string.Format("Flag is : {0}.", m.Groups["Flag"].Value) ,否则,替换将仅包含到期消息。

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

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