用对特定捕获组的操作替换正则表达式的所有匹配项 [英] Replace all matches of regex with manipulation on specific capturing group

查看:38
本文介绍了用对特定捕获组的操作替换正则表达式的所有匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有不同的 Xml 字符串,它们可以包含以下格式的一个或多个部分:

I have different Xml strings that can contain one or more parts in the following format:

<ns1:AcctId>47862656</ns1:AcctId>

中间的值可以改变.我想用一个操纵值(从 BBAN 到 IBAN,具体来说)替换这个 <ns:1:AcctId> 元素的所有出现.

The value in the middle can change. I want to replace all occurences of this <ns:1:AcctId> element with a manipulated value (from BBAN to IBAN to be specific).

我在带有属性 Xml(一个 XML 字符串)的 XMLModel 类中创建了以下方法:

I have made the following method in the XMLModel class with a property Xml (a XML-string):

string regexString = "(<ns1:AcctId>)(?<AcctId>.*?)(</ns1:AcctId>)";
Regex regex = new Regex(regexString);
Match match = regex.Match(Xml);
string AcctId = match.Groups["AcctId"].Value;
string IBANizedAcctId = IBANHelper.ConvertBBANToIBAN(AcctId);

Xml = Regex.Replace(Xml, regexString, string.Format("$1{0}$3", IBANizedAcctId));

这里的想法是 regexString 有三个捕获组,我用转换为 IBAN 的帐号替换中间值(帐号).

The idea here is that the regexString has three capturing groups, and I replace the middle value (the account number) with the account number converted to IBAN.

不幸的是,这段代码不起作用:1) 它确实捕获了 AcctId 的值,但它没有正确替换它,因为它丢失了最后一个 </ns1:AcctId> 部分.2) 它用第一个捕获的值替换匹配的所有出现,而它应该用捕获的特定值替换每个出现.

Unfortunately, this code does not work: 1) it does capture the value of AcctId, but it does not replace it correctly since it loses the last </ns1:AcctId> part. 2) it replaces all occurences of the match with the value captured in the first one, while it should replace every occurence with the specific one captured.

在 C# 中有没有办法做到这一点?如果是这样,有人能给我一些关于如何做到这一点的指示吗?任何帮助将不胜感激.

Is there any way to do this in C#? And if so, can someone give me some pointers on how to do this? Any help would be greatly appreciated.

推荐答案

除了通常不要使用正则表达式来操作 XML.

Apart from the usual don't use regex to manipulate XML.

string regex = "(?<=<ns1:AcctId>).*?(?=</ns1:AcctId>)";
Xml = Regex.Replace(Xml, regex, delegate(Match m) {
                           return IBANHelper.ConvertBBANToIBAN(m.Value);
                         });

这使用积极向前看和向后看,以便匹配只是帐号,然后重载到 Regex.Replace 需要匹配评估器.

This uses positive look ahead and look behind so that the match is just the account number and then the overload to Regex.Replace the takes a match evaluator.

这篇关于用对特定捕获组的操作替换正则表达式的所有匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆