1
Regex.Replace("a b c a b c", "a", "*")

returns

"* b c * b c"

Is there a simple way to replace only the first occurence, such that the result is

"* b c a b c"

Cannot find a RegExOption that would limit the replacement. In particular

Regex.Replace("a b c a b c", "a", "*", RegexOptions.Multiline)
Regex.Replace("a b c a b c", "a", "*", RegexOptions.Singleline)

do not make any difference - obviously. There are not much more options however.

1
  • is there any replaceFirst option. Commented Mar 9, 2015 at 9:07

2 Answers 2

5

Use the appropriate overload

Regex rgx = new Regex("a");
string result = rgx.Replace("a b c a b c", "*", 1); // * b c a b c
Sign up to request clarification or add additional context in comments.

Comments

1

Use capturing group along with the starting anchor.

Regex.Replace("a b c a b c", "^([^a]*)a", "$1*")

DEMO

^([^a]*) captures all the characters which exists before the first a. And the following a on the above regex matches only the first a. So by replacing the matched chars with the characters present inside the group index 1 plus * will give you the desired output.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.