I want to replace the first occurrence in a given string.
How can I accomplish this in .NET?
|
Example:
EDIT: As @itsmatt mentioned, there's also Regex.Replace(String, String, Int32), which can do the same, but is probably more expensive at runtime, since it's utilizing a full featured parser where my method does one find and three string concatenations. EDIT2: If this is a common task, you might want to make the method an extension method:
Using the above example it's now possible to write:
|
|||||
|
As itsmatt said Regex.Replace is a good choice for this however to make his answer more complete I will fill it in with a code sample:
The third parameter, set to 1 in this case, is the number of occurrences of the regex pattern that you want to replace in the input string from the beginning of the string. I was hoping this could be done with a static Regex.Replace overload but unfortunately it appears you need a Regex instance to accomplish it. |
|||
|
Take a look at Regex.Replace. |
|||
|
Taking the "first only" into account, perhaps:
? Or more generally:
Then:
|
|||
|
In C# syntax:
|
|||||
|
C# extension method that will do this:
Enjoy |
|||
Assumes that
If you need to replace the first occurrence of |
|||
|
And because there is also VB.NET to consider, I would like to offer up:
|
||||
|
One of the overloads of
|
|||
|
Regex.Replace, especially RegEx.Replace(string, string, int), is probably what you're looking for. That or String.IndexOf which will give you the index and then you can cut and rebuild the string with the new text you want. An example demonstrating the latter (as first demonstrated by @David Humpohl):
|
|||||
|
|
|||
|
will find first |
||||
|