【问题标题】:RegEx to replace special characters in a string with space ? asp.net c#正则表达式用空格替换字符串中的特殊字符? ASP.NET C#
【发布时间】:2011-05-18 18:24:05
【问题描述】:
string inputString = "1/10 EP Sp'arrowha?wk XT R;TR 2.4GHz Red";
//Characters Collection: (';', '\', '/', ':', '*', '?', ' " ', '<', '>', '|', '&', ''')
string outputString = "1 10 EP Sp arrowha wk XT R TR 2.4GHz Red";

【问题讨论】:

  • 您是否正在尝试对 SQL 进行某种转义?
  • 我知道我参加聚会迟到了,但是……这是个问题?有 9 票?天哪!

标签: c# asp.net regex


【解决方案1】:

关于以下代码的完整披露:

  • 未经测试
  • 我可能搞砸了new Regex(...)中的字符转义;
  • 我实际上并不了解 C#,但我可以通过 Google 搜索 "C# string replace regex"land on MSDN

    Regex re = new Regex("[;\\/:*?\"<>|&']");
    string outputString = re.Replace(inputString, " ");
    

这是正确的代码:

string inputString = "1/10 EP Sp'arrowha?wk XT R;TR 2.4GHz R\\ed";
Regex re = new Regex("[;\\\\/:*?\"<>|&']");
string outputString = re.Replace(inputString, " ");
// outputString is "1 10 EP Sp arrowha wk XT R TR 2.4GHz R ed"

演示:http://ideone.com/hrKdJ

还有:http://www.regular-expressions.info/

【讨论】:

  • ' 移动到char 类中,我也会使用+,比如"[;\\/:*?\"&lt;&gt;|&amp;']+"
  • @Matt Ball,我知道你可能对 OP 没有先用谷歌搜索感到不安,但这并不意味着你必须刻薄或讽刺。
  • @Xaisoft 的意思是披露,完全没有消极的意思。我已经改写了它;如果它仍然很糟糕,请告诉我。
  • @Matt Ball,一切都很好。我不认为你是消极的,我认为你对人们在发帖前至少不尝试感到不安。
  • 如果我想替换 [ 和 ] 怎么办?
【解决方案2】:
string outputString = Regex.Replace(inputString,"[;\/:*?""<>|&']",String.Empty)

【讨论】:

    【解决方案3】:

    这里是替换特殊字符的Java代码

    String inputString = "1/10 EP Sp'arrowha?wk XT R;TR 2.4GHz R\\ed";
    String re = "[;\\\\/:*?\"<>|&']";
    Pattern pattern = Pattern.compile(re);
    Matcher matcher = pattern.matcher(inputString);
    String outputString = matcher.replaceAll(" ");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多