Reputation: 41
I am trying to replace strings in a large amount of data and I was hoping to use regular expression for certain updates that I have to make to the text, I should point out that I am fairly new to regular expressions.
Show here is what I am trying to achieve. Within the text I am converting we have the following data {0} {1} {2}, this has to be converted to a new format so {0} becomes %{ param0 } , {1} becomes %{ param1 }, {2} becomes %{ param2 }.
There is no limit on what the number could be, so far it has reached 16 and may go up in the future (It should be pointed out that the number is actually a string at this point). This is code I have so far but it only updates the value to {param0}. Also if the text contains more than one instance it only updates the first.
NewText = Regex.Replace(NewText , @"(?<=\{).*(?=\})", "param$0");
Thanks, Brendy
Upvotes: 0
Views: 1664
Reputation: 14468
The MSDN documentation for Regex.Replace says
The replacement parameter specifies the string that is to replace each match in input. replacement can consist of any combination of literal text and substitutions. For example, the replacement pattern a*${test}b inserts the string "a*" followed by the substring that is matched by the test capturing group, if any, followed by the string "b". The * character is not recognized as a metacharacter within a replacement pattern.
This means that you can simply use a capturing group to keep the number around. Try
newText = Regex.Replace(newText, @"\{(?<Num>\d+)\}", "%{param${num}}");
Upvotes: 0
Reputation: 183456
You can write:
NewText = Regex.Replace(NewText , @"\{(0|[1-9]\d*)}", "%{ param$1 }");
Regarding this:
Also if the text contains more than one instance it only updates the first.
What's really happening is that if your string is {0} {1} {2}
, then your code will replace the 0} {1} {2
part with param0} {1} {2
, giving the end result {param0} {1} {2}
. So it looks like it's only updating the first instance, but really what it's doing is updating all instances as though they were a single instance. This is because the .*
notation swallows as much as it can while still allowing the regex to match.
Upvotes: 1
Reputation: 6639
Unless you really need to use regex to find your pattern, you might want to consider String.Replace
or StringBuilder.Replace
. Refer to these for more info: Regex.Replace, String.Replace or StringBuilder.Replace which is the fastest? or Memory Efficiency and Performance of String.Replace .NET Framework
Upvotes: 0