RegEx替换错误的符号C#

时间:2012-03-22 10:53:09

标签: c# regex replace

我需要用短划线字符“ - ”

替换字符串中的字符和数字以外的错误符号
var myString = "this=is+/* wrong!@# string^&*(";

我用

Regex.Replace(myString, "[^0-9a-zA-Z]+", "-");

因此它是“这是----错---- ---- ----”

但我需要“这是错误的字符串”

我的RegEx应该更改什么?谢谢!

2 个答案:

答案 0 :(得分:4)

无法重现:

using System;
using System.Text.RegularExpressions;

class Test
{
    static void Main()
    {
        var input = "this=is+/* wrong!@# string^&*(";
        var output = Regex.Replace(input, "[^0-9A-Za-z]+", "-");
        Console.WriteLine(output);
    }                   
}

输出:this-is-wrong-string-

所以你可能想用TrimEnd('-')来摆脱尾随的“ - ”,但对我来说看起来不错。将您的代码与我的简短但完整的程序进行比较,如果您找不到错误,请提出类似的简短但完整的程序演示问题。

答案 1 :(得分:2)

你的正则表达式对我有用:

PS> "this=is+/* wrong!@# string^&*(" -replace '[^0-9a-zA-Z]+','-'
this-is-wrong-string-

但您之后需要删除跟踪-