I'm trying to understand Regex Replace Method. I wrote a function that should insert a space before the first capital letter that is not preceded by a capital letter.
var tmpDisplay = Regex.Replace(name, "([^A-Z ])([A-Z])", "$1 $2");
When I run this it replaces all of the capital letters that are not preceded by a capital letter.
I Checked MSDN and it doesn't seem to mention that regex replaces act global on the string instead of matching just the first case.
How can I only replace a single value? Could anyone provide the documentation about this issue?
The static Regex.Replace
method has no max occurrences argument, but the class instance has:
var rx = new Regex(@"([^A-Z ])([A-Z])");
Console.WriteLine(rx.Replace("NamePeteParker", "$1 $2", 1)); // Replace just once
^^
See the IDEONE demo
From MSDN:
Regex.Replace Method (String, MatchEvaluator, Int32)
Within a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a string returned by a MatchEvaluator delegate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With