首页 新闻 会员 周边

求一个简单正则表达式

0
悬赏园豆:50 [已关闭问题]

返回字符串中英文和数字部分。比如:

1. abcd博客园
返回:abcd 

2.  visual studio 2005和visual studion 2008的区别
返回:visual studio 2005和visual studion 2008

 

好好学习,天天向上的主页 好好学习,天天向上 | 初学一级 | 园豆:68
提问于:2010-03-16 14:50
< >
分享
其他回答(1)
0
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#中正则表达式测试代码如上,可根据需求更改!

西越泽 | 园豆:10775 (专家六级) | 2010-03-16 15:11
0

楼主的意思是排除字串中的中文字符还是仅保留英文和数字?

“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



邀月 | 园豆:25475 (高人七级) | 2010-03-16 23:11
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册