Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex.Replace: replace only first one found [duplicate]

Tags:

c#

regex

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

How do I make Regex.Replace replace only the first found pattern?

like image 983
Luke Avatar asked Jun 16 '11 12:06

Luke


People also ask

How do you replace a section of a string in regex?

The \[[^\]]*]\[ matches [ , then any 0+ chars other than ] and then ][ . The (...) forms a capturing group #1, it will remember the value that you will be able to get into the replacement with $1 backreference. [^\]]* matches 0+ chars other than ] and this will be replaced.

How does regex replace work C#?

In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string. In a specified input string, replaces all substrings that match a specified regular expression with a string returned by a MatchEvaluator delegate.

What replaces one or many matches with a string?

subn() If you want to replace a string that matches a regular expression (regex) instead of perfect match, use the sub() of the re module. In re. sub() , specify a regex pattern in the first argument, a new string in the second, and a string to be processed in the third.

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.


1 Answers

What about Regex.Replace ( String, String, Int32 ) (MSDN) ?

An example:

Regex rgx = new Regex(pattern); string result = rgx.Replace(str, replacement, 1); // The 1 makes the difference 
like image 189
cimnine Avatar answered Sep 20 '22 22:09

cimnine