日期:2014-05-18  浏览次数:20950 次

再问正则表达式,为什么字符串过长之后就失效了?
string   PhoneNumberString   =   "03728566232,13137132770,13237132770,13337132770,13437132770,13537132770,13637132770,13737132770,13837132770,13937132770,037155555555,02155555555,01033333333,03736566526 ";
string   result1   =   Regex.Replace(PhoneNumberString,   @ "1(?:3[0-3]|53)[0-9]{8}(?:,|$)|0([0-9]{10})(?:,|$)|0([0-9]{11})(?:,|$) ",   " ");   //移动
string   result2   =   Regex.Replace(PhoneNumberString,   @ "1(?:3[4-9]|5[89])[0-9]{8}(?:,|$)|0([0-9]{10})(?:,|$)|0([0-9]{11})(?:,|$) ",   " ");   //联通
string   result3   =   Regex.Replace(PhoneNumberString,   @ "1(?:3[0-3]|53)[0-9]{8}(?:,|$)|1(?:3[4-9]|5[89])[0-9]{8}(?:,|$) ",   " ");   //小联通  
MessageBox.Show( "移动: "   +   result1   +   "\n联通: "   +   result2   +   "\n小灵通: "   +   result3);
---------------------
//上面程序运行没问题,很正常
可是如果是从文本文件里把10万行数据读到String里,它就失效了.
为什么呢?有什么办法解决吗?

------解决方案--------------------
尝试把3个正则合并起来。
------解决方案--------------------
{
string PhoneNumberString = "03728566232,13137132770,13237132770,13337132770,13437132770,13537132770,13637132770,13737132770,13837132770,13937132770,037155555555,02155555555,01033333333,03736566526 ";
string result1 =GetPhone(PhoneNumberString,@ "13[4-9]\d{8} ");//移动
string result2 =GetPhone(PhoneNumberString,@ "13[0-3]\d{8} ");//联通
string result3 =GetPhone(PhoneNumberString,@ "(? <=^|,)[^1]\d+(?=,|$) ");//小灵通
}
/// <summary>
/// 获取要的电话
/// </summary>
/// <param name= "inputString "> 输入字符串 </param>
/// <param name= "pattern "> 正则 </param>
/// <returns> 匹配后字符串 </returns>
private string GetPhone(string inputString ,string pattern)
{
StringBuilder sb=new StringBuilder();
MatchCollection mc = Regex.Matches(inputString ,pattern);
foreach(Match m in mc)
{
sb.Append(m.Value);
sb.Append( ", ");
}
return sb.ToString();
}
//类似于这样的写法,会及大的节约内存(正则不是很准15开头的不知道)
//另,一行行匹配是最好的解决方案