0

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);
3
  • 2
    Did you try var result = Regex.Replace(inputString, @"#", Environment.NewLine);? Commented Jul 5, 2012 at 13:35
  • 2
    Why not use string.Replace instead in such a simple case? Commented Jul 5, 2012 at 13:35
  • That is what I ended up using. Thanks! Commented Jul 5, 2012 at 13:51

3 Answers 3

5

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Wow I feel dumb, that is it. It's only Thrusday morning and it has been a long day! Cheers!
2

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

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

Comments

0

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.

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.