简体   繁体   English

正则表达式替换不替换

[英]Regex.Replace not replacing

I have am using regex.replace to replace a '#' character with a Environment.Newline. 我正在使用regex.replace用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);

Regex.Replace doesn't change the parameter you passed in. It returns the results as a new string. Regex.Replace不会更改您传入的参数。它将结果作为新字符串返回。

Try this: 尝试这个:

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

Of course, Regex is a bit overkill for such a simple replacement. 当然,对于这种简单的替换,Regex有点过大。 String.Replace would be enough in that case (note: String.Replace also doesn't modify the parameter, but returns a new string). 在这种情况下, String.Replace就足够了(注意: String.Replace也不会修改参数,而是返回一个新的字符串)。

您不需要正则RegEx ,更简单:

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

As Dr. ABT mentioned, you need to return the Replace method into a variable. 正如ABT博士所述,您需要将Replace方法返回到变量中。 So, you could do: 因此,您可以执行以下操作:

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

This will update the inputString variable with the required replacements. 这将使用所需的替换项更新inputString变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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