0

I have a paragraph of text read from a file using C# File.ReadAllText(). Say this was my output:

See [a car] is a wheeled, self-powered motor vehicle used for transportation 
and a product of the automotive industry. 

Most definitions of the term specify that [a car] is designed to run 
primarily on roads, to have seating for one to eight people, to typically 
have four wheels with tyres

I want to match and replace the phrase "a car" but only the SECOND occurrence with "test string". Brackets [ ] added for easier reading but they are not really present within the file text. The regexes I've seen on StackOverflow only replace a character/word within a string that has no line breaks. How can I search an entire paragraph of text and do a regex replace on the second occurrence of a phrase?

invulnarable27
  • 591
  • 5
  • 22
  • Unless you use `RegexOptions.MultiLine` there is no concept of "line" in Regex. A single `string` is a single `string`. end of lines (`\r\n` or `\n`) are simply "spaces" (in the `\s` meaning) – xanatos Apr 12 '17 at 07:57
  • 2
    Simple solution: `var rx = new Regex(Regex.Escape("[a car]")); int found = 0; string text2 = rx.Replace(text, x => found++ == 1 ? "[Some Replace Text]" : x.Value);` – xanatos Apr 12 '17 at 08:05
  • @xanatos Simple and elegant solution, thanks! – invulnarable27 Apr 12 '17 at 20:52

0 Answers0