Replace all matches of regex with manipulation on specific capturing group

后端 未结 2 2017
终归单人心
终归单人心 2021-01-26 00:36

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

47862656

The valu

相关标签:
2条回答
  • 2021-01-26 00:40

    You shouldn't use regex to manipulate XML, they're not the appropriate tool for that and won't always work. For instance, the XML file could use a namespace prefix other than ns1, mapped to the same namespace, and it would be semantically equivalent, but your regex wouldn't work anymore.

    You should use an XML parser instead; the easiest to use is Linq to XML:

    var doc = XDocument.Parse(Xml);
    var ns1 = XNamespace.Get("http://TheNamespaceMappedToTheNs1Prefix");
    var elements = doc.Descendants(ns1 + "AcctId");
    foreach (var e in elements)
    {
        e.Value = IBANHelper.ConvertBBANToIBAN(e.Value); 
    }
    Xml = doc.ToString();
    
    0 讨论(0)
  • 2021-01-26 00:49

    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);
                             });
    

    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.

    0 讨论(0)
提交回复
热议问题