日期:2014-05-17 浏览次数:20458 次
string str1 = @"WWW123-112EF2211/V1.0字字字字"; string str2 = @"QWE234A-123AB32/V2.2字字字字字"; //结果一: WWW123(V1.0)-112EF2211/ //结果二: QWE234(V2.2)-123AB32/A if (str2.Contains("-") && str1.Contains("/V")) { if (str2.StartsWith("WWW") || str2.StartsWith("QWE")) { //匹配 str2 = System.Text.RegularExpressions.Regex.Replace(str2, @"(WWW|QWE)(\d+)([A-Z]*?)-(\d+[A-Z]+\d+)/(V\d+\.\d+)", @"$1$2($5)-$4/$3"); str2 = System.Text.RegularExpressions.Regex.Replace(str2, @"[\u4e00-\u9fa5]+", "");//去掉中文 Console.WriteLine(str2); } else { Console.WriteLine("源字符串不以WWW和QWE开头"); } } else { Console.WriteLine("源字符串不包含-和/V"); } /* QWE234(V2.2)-123AB32/A */
------解决方案--------------------
更完整点
string str1 = @"WWW123-112EF2211/V1.0字字字字"; string str2 = @"QWE234A-123AB32/V2.2字字字字字"; List<string> list = new List<string>(); List<string> matchList = new List<string>(); list.Add(str1); list.Add(str2); //结果一: WWW123(V1.0)-112EF2211/ //结果二: QWE234(V2.2)-123AB32/A foreach (string str in list) { if (str.Contains("-") && str.Contains("/V")) { if (str.StartsWith("WWW") || str.StartsWith("QWE")) { string newstr = String.Empty; //匹配 newstr = System.Text.RegularExpressions.Regex.Replace(str, @"(WWW|QWE)(\d+)([A-Z]*?)-(\d+[A-Z]+\d+)/(V\d+\.\d+)", @"$1$2($5)-$4/$3"); newstr = System.Text.RegularExpressions.Regex.Replace(str, @"[\u4e00-\u9fa5]+", "");//去掉中文 matchList.Add(newstr); } else { Console.WriteLine("源字符串不以WWW和QWE开头"); } } else { Console.WriteLine("源字符串不包含-和/V"); } } matchList.ForEach(X => Console.WriteLine(X)); /* WWW123(V1.0)-112EF2211/ QWE234(V2.2)-123AB32/A * /
------解决方案--------------------
string[] arrStr = new string[] { "WWW123-112EF2211/V1.0字字字字", " QWE234A-123AB32/V2.2字字字字字" }; Regex reg = new Regex(@"(?is)(WWW|QWE)(\d{3})([^-]+?)?(-[^/]+?/)(.{4}).+"); foreach (string str in arrStr) { Response.Write(reg.Replace(str, "$1$2($5)$4$3") + "<br/>"); } //WWW123(V1.0)-112EF2211/ //QWE234(V2.2)-123AB32/A