我需要更换,除非我的字符串与破折号字符和数字错误的符号错误的符号“ - ”正则表达式替换C#
var myString = "this=is+/* [email protected]# string^&*(";
我用
Regex.Replace(myString, "[^0-9a-zA-Z]+", "-");
,因此它是“这个-is ---- ----错误字符串----”
但我需要‘这 - 是 - 错串’
我应该改变我我的RegEx。谢谢!
我需要更换,除非我的字符串与破折号字符和数字错误的符号错误的符号“ - ”正则表达式替换C#
var myString = "this=is+/* [email protected]# string^&*(";
我用
Regex.Replace(myString, "[^0-9a-zA-Z]+", "-");
,因此它是“这个-is ---- ----错误字符串----”
但我需要‘这 - 是 - 错串’
我应该改变我我的RegEx。谢谢!
无法重现:
using System;
using System.Text.RegularExpressions;
class Test
{
static void Main()
{
var input = "this=is+/* [email protected]# string^&*(";
var output = Regex.Replace(input, "[^0-9A-Za-z]+", "-");
Console.WriteLine(output);
}
}
输出:this-is-wrong-string-
所以,你可能需要使用TrimEnd('-')
摆脱尾随的“ - ”,但除此之外,它看起来好像没什么问题。比较你的代码和我的简短但完整的程序,如果你找不到有什么问题,拿出一个类似的简短但完整的程序,其中显示的问题。
你的正则表达式的工作对我来说:
PS> "this=is+/* [email protected]# string^&*(" -replace '[^0-9a-zA-Z]+','-'
this-is-wrong-string-
但是,你需要删除尾随其后-
。
无法重现。 Expresso提供正确的输出。在运行'Replace'之前,你还做了其他的事情吗? – Shimrod 2012-03-22 10:59:26
用expresso试了一下。我得到{this-is-wrong-string-}作为输出,这看起来是正确的给你的正则表达式。 – Gishu 2012-03-22 11:00:13
我已经试过你的示例代码,结果是你需要用一个短划线。 – 2012-03-22 11:01:02