string s1 = "abcd博客园cnblogs";
string s2 = "Visual Studio 2005和Visual Studio 2008那个好";
string result = string.Empty, result1 = string.Empty;
Regex regex = new Regex(@"[a-zA-Z0-9]*", RegexOptions.Multiline | RegexOptions.IgnoreCase);
MatchCollection mc = regex.Matches(s1);
foreach (Match match in mc)
if (match.Success)
result += match.Value;
MatchCollection mc1 = regex.Matches(s2);
foreach (Match match in mc1)
if (match.Success)
result1 +=" "+ match.Value;
C#中正则表达式测试代码如上,可根据需求更改!
楼主的意思是排除字串中的中文字符还是仅保留英文和数字?
“visual studio 2005” “visual studion 2008”这个应视为排除中文字符
public static void Main(string[] args)
{
string oldstr = "abcd博客园cnblogs,visual studio 2005和visual studion 2008的区别";
Console.WriteLine(FilterChIneseChar(oldstr));
Console.ReadKey();
}
private static string FilterChIneseChar(string oldstring)
{
if (string.IsNullOrEmpty(oldstring))
{
return string.Empty;
}
////if (!IsChinese(oldstring))
////{
//// return oldstring;
////}
System.Text.StringBuilder result = new System.Text.StringBuilder();
for (int i = 0; i < oldstring.Length; i++)
{
char ch = oldstring[i];
if (!IsChinese(ch))
{
result.Append(ch.ToString());
}
}
return result.ToString();
}
#region RegularExpression
public static bool IsChinese(string text)
{
return System.Text.RegularExpressions.Regex.Match(text, ConstChineseRegex, System.Text.RegularExpressions.RegexOptions.Compiled).Success;
}
public static bool IsChinese(char ch)
{
return IsChinese(Convert.ToString(ch));
}
public const string ConstChineseRegex = @"^[\u4e00-\u9fa5]+$";
#endregion
结果:abcdcnblogs,visual studio 2005visual studion 2008