0

I want to capture a part of an XML string and replace a captured value with a new one.

I have the following code:

Regex regex = new Regex("<ns1:AcctId>(?<AcctId>.*?)</ns1:AcctId>");
Match match = regex.Match(Xml);

string AcctId = match.Groups["AcctId"].Value;

string IBANizedAcctId = IBANHelper.ConvertBBANToIBAN(AcctId);

newXml = Regex.Replace(oldXml, regex, IBANizedAcctId); //DOES NOT WORK!

So I want to capture the AcctId in the ns1:AcctId XML element. Then I want to replace this one with a new value by converting the BBAN to IBAN and replace the value. The first part works, but I do not know how to accomplish the last part (I did find an idea here, but I do not understand it).

I hope someone can help me out!

Community
  • 1
  • 1
user2609980
  • 10,264
  • 15
  • 74
  • 143
  • ok... for some reason it won't let me post my answer... :( – MaxOvrdrv May 05 '14 at 17:05
  • here are the 2 changes i made to your existing code: Match match = regex.Match(oldXml); -and- string newXml = oldXml.Replace(AcctId, IBANizedAcctId); – MaxOvrdrv May 05 '14 at 17:06
  • Cannot answer it either: but I found this solution thanks to [this](http://stackoverflow.com/questions/6005609/replace-only-some-groups-with-regex#6005637) answer: I know that the last part should be: `Xml = Regex.Replace(Xml, regexString, string.Format("$1{0}$3", IBANizedAcctId));` where the regexString has three capturing groups: `string regexDestAcctIntString = "()(?.*?)()";` The `$1` and `$3` refer to respectively the first and third capturing group and replace the middle with the new value. 80% sure it works. – user2609980 May 05 '14 at 17:13
  • @MaxOvrdrv that is even more logical. :) – user2609980 May 05 '14 at 17:14
  • try it out... mine will work 100% as well, and across your entire Xml string. Not just the match. Up to you ;) – MaxOvrdrv May 05 '14 at 17:15

1 Answers1

1
Regex regex = new Regex("<ns1:AcctId>(?<AcctId>.*?)</ns1:AcctId>");
Match match = regex.Match(oldXml);

string AcctId = match.Groups["AcctId"].Value;

string IBANizedAcctId = IBANHelper.ConvertBBANToIBAN(AcctId);

newXml = oldXml.Replace(AcctId, IBANizedAcctId); //should work...
MaxOvrdrv
  • 1,780
  • 17
  • 32
  • I want to capture all occurences of ` *** `, and they can contain different numbers. – user2609980 May 06 '14 at 07:38
  • I accepted the answer since it does work! But my requirement now is a bit different. I made a new question for that one [here](http://stackoverflow.com/questions/23489039/replace-al-matches-of-regex-with-manipulation-on-specific-capturing-group). – user2609980 May 06 '14 at 07:57