Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Replace Matches All instead of single

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?

like image 755
johnny 5 Avatar asked Mar 12 '23 08:03

johnny 5


1 Answers

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.

like image 147
Wiktor Stribiżew Avatar answered Mar 25 '23 06:03

Wiktor Stribiżew