Share via

How do regular expressions replace multiple matches?

奇 卢 181 Reputation points
2021-06-12T13:08:23.697+00:00

Sample string: "Print Computer information" (Except double quotes)

I want to add "a" after "print" and "operation" before "information".

So the result string is: "Print a Computer operation information"

My regular expression pattern is: @"(Print)(?:.+)(?=information)"

My replacement string is: “$1 a operation”.

But the result is not correct... How to replace it?

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

Answer accepted by question author

Viorel 126.9K Reputation points
2021-06-12T16:15:25.127+00:00

I think that you can use two replaces, or:

string sample = "Print Computer information";
string result = Regex.Replace( sample, @"(Print )(.*)( information)", "$1a $2 operation$3" );

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.