【问题标题】:Replace string using Regex.Replace使用 Regex.Replace 替换字符串
【发布时间】:2013-02-05 10:23:52
【问题描述】:

我有一个字符串

string findText = "Paid part-time job (under 8 hours per week)";

我想使用 Regex.Replace() 将这个字符串替换为其他字符串 (replaceText = "Paid for job"),如下所示:

Regex r = new Regex(findText, RegexOptions.IgnoreCase);
findText = r.Replace(findText, replaceText);

但问题是这个字符串没有被替换,可能是由于文本中存在大括号。

谁能建议如何使用Regex.Replace() 替换整个字符串?

【问题讨论】:

  • 所以你想把“part-time”换成“for”?
  • 不,我想用“Paid for Job”或任何其他字符串替换整个字符串。我想要的是我应该能够替换整个字符串,即使它包含特殊字符。由于特殊字符,它不会被使用 regexOptions 替换

标签: c#


【解决方案1】:

这里完全不需要使用正则表达式。
只需使用string.Replace

var result = original.Replace(findText, replaceText);

【讨论】:

  • 其实我这里需要使用正则表达式,因为这里要考虑区分大小写。
  • 感谢您的解决方案...!!
【解决方案2】:

对于您的示例,使用字符串替换更容易:

string result = yourString.Replace(findText, replaceText);

但如果你仍然想使用正则表达式,你应该转义大括号,例如这样:

string findText = "Paid part-time job [(]under 8 hours per week[)]";

并称它为 pattern 而不是 findText :)

【讨论】:

  • 其实这个 findText 来自某个数据库,所以无法逃脱大括号...
猜你喜欢
  • 1970-01-01
  • 2011-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-20
相关资源
最近更新 更多