【问题标题】:Replacing multiple string Replace() with a single Regex.Replace()用单个 Regex.Replace() 替换多个字符串 Replace()
【发布时间】:2012-07-18 19:54:53
【问题描述】:

如果我正在做类似的事情:

someString.Replace("abc","").Replace("def","").Replace(@"c:\Windows","")

如何用

替换它
Regex.Replace(someString," \\here I don't know what the pattern should be")

我试过了:

Regex.Replace(someString, @"(?:abc|def|c:\Windows)")

但是没用

更新...

问题是当我通过这样的路径时

Regex.Replace(someString, @"(?:abc|def|"+aPath+")")

【问题讨论】:

  • 确保所有反斜杠都被转义。 \ 应该是 \\

标签: regex c#-4.0


【解决方案1】:
`But it didnt work` doesn't say much helpfull!

试试这个:

someString = Regex.Replace(someString, @"(?:abc|def|ghi|c:\\Windows)", "")

当我尝试它时它确实有效。我认为您的代码不起作用的原因是您忘记了替换字符串,并且您必须转义路径中的反斜杠。

【讨论】:

    【解决方案2】:

    我假设“不起作用”的东西是您的 C:\windows 替代品。你需要

    someString = Regex.Replace(someString, @"(?:abc|def|C:\\windows)","");
    

    问题是您需要转义反斜杠。未转义的反斜杠在正则表达式中有意义。特别是,在这种情况下,\W 实际上匹配任何非字母数字字符。

    编辑转义任意字符串,可以使用Regex.Escape(yourString);

    【讨论】:

    • 如果我传递这样的路径怎么办:Regex.Replace(someString, @"(?:abc|def|"+aPath+","")
    猜你喜欢
    • 2013-02-05
    • 1970-01-01
    • 2010-11-19
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    相关资源
    最近更新 更多