tympaniplayer
tympaniplayer

Reputation: 171

Regex.Replace not replacing

I have am using regex.replace to replace a '#' character with a Environment.Newline. However it is not returning the expected results. It is just returning the same input string. Here is my code.

Regex.Replace(inputString, @"#", Environment.NewLine);

Upvotes: 0

Views: 1354

Answers (3)

Botz3000
Botz3000

Reputation: 39610

Regex.Replace doesn't change the parameter you passed in. It returns the results as a new string.

Try this:

inputString = Regex.Replace(inputString, @"#", Environment.NewLine);

Of course, Regex is a bit overkill for such a simple replacement. String.Replace would be enough in that case (note: String.Replace also doesn't modify the parameter, but returns a new string).

Upvotes: 5

Neil Knight
Neil Knight

Reputation: 48547

As Dr. ABT mentioned, you need to return the Replace method into a variable. So, you could do:

inputString = Regex.Replace(inputString, @"#",Environment.NewLine);

This will update the inputString variable with the required replacements.

Upvotes: 0

Gabe
Gabe

Reputation: 50493

You don't need a RegEx for what you're doing, simpler:

inputString = inputString.Replace("#", Environment.NewLine);

Upvotes: 2

Related Questions