简体   繁体   中英

How to replace all instance of one word with another in C#

How to replace all instances of a word with another in C#? Is there a RegexOption to specify replacing all instances like /g in Perl?

Perl:

$line = "Oranges and Apples.  Apples and Oranges";
$line =~ s/Oranges/Pears/g;

C#:

string line = "Oranges and Apples.  Apples and Oranges";
line = Regex.Replace(line, @"Oranges", "Pears", ????);

The part I'm missing is indicated by ???? in the C# snippet.

In C#, the Regex.Replace function is implicitly global, so that is the equivalent of the g modifier in Perl. You don't need any RegexOptions since there are no other flags on the Perl substitution.

line = Regex.Replace(line, "Oranges", "Pears");

If you don't want the global behavior for some reason, you need to use an instance, rather than the static method:

 line = (new Regex("Oranges")).Replace(line, "Pears", 1);

But you should probably use String.Replace() for this specific case, since this isn't really a pattern:

line = line.Replace("Oranges", "Pears");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM