Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Regex search/replace only first occurrence in a string in .NET?

Tags:

.net

regex

People also ask

How do you replace the first occurrence of a character in a string?

Use the replace() method to replace the first occurrence of a character in a string. The method takes a regular expression and a replacement string as parameters and returns a new string with one or more matches replaced.

How do you replace all occurrences of a regex pattern in a string?

count : Maximum number of pattern occurrences to be replaced. The count must always be a positive integer if specified. . By default, the count is set to zero, which means the re. sub() method will replace all pattern occurrences in the target string.

Can I use regex in replace?

How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.


From MSDN:

Replace(String, String, Int32)   

Within a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a specified replacement string.

Isn't this what you want?


Just to answer the original question... The following regex matches only the first instance of the word foo:

(?<!foo.*)foo

This regex uses the negative lookbehind (?<!) to ensure no instance of foo is found prior to the one being matched.


You were probably using the static method. There is no (String, String, Int32) overload for that. Construct a regex object first and use myRegex.Replace.


In that case you can't use:

string str ="abc546_$defg";
str = Regex.Replace(str,"[^A-Za-z0-9]", "");

Instead you need to declare new Regex instance and use it like this:

string str ="abc546_$defg";
Regex regx = new Regex("[^A-Za-z0-9]");
str = regx.Replace(str,"",1)

Notice the 1, It represents the number of occurrences the replacement should occur.