日期:2014-05-17 浏览次数:20456 次
StreamReader reader = new StreamReader("c:\\1.txt",Encoding.Default); while (!reader.EndOfStream) { int num = 0; string str = reader.ReadLine(); Regex reg = new Regex(@"(?is)\d+"); MatchCollection mc = reg.Matches(str); foreach (Match m in mc) { num += Convert.ToInt32(m.Value); } MessageBox.Show(num.ToString()); }
------解决方案--------------------
^\d+就可以了。
------解决方案--------------------
应该没什么简单的办法吧
string text = @"5 10ml 20ML 120ml*4 360+120ML 360+100ml 500ML+300ML"; text = Regex.Replace(text, "[a-zA-Z]", ""); text = Regex.Replace(text, @"(?!\d+)(\*.*)", ""); var matches = Regex.Matches(text, @"(\d+)(\+(\d+))*"); foreach (Match match in matches) { if (match.Groups[2].Success) Console.WriteLine(Convert.ToInt32(match.Groups[1].Value) + Convert.ToInt32(match.Groups[3].Value)); else Console.WriteLine(Convert.ToInt32(match.Groups[1].Value)); }
------解决方案--------------------
string[] source = { "5", "10ml", "20ML", "120ml*4", "360+120ML", "360+100ml", "500ML+300ML", }; System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"([^\d\+\*])|(\*\d+)"); System.Data.DataTable dt = new System.Data.DataTable(); foreach (string s in source) { string result = dt.Compute(reg.Replace(s, string.Empty), null).ToString(); }
------解决方案--------------------
string[] strs ={ "5", "10ml", "20ML", "120ml*4", "360+120ML", "360+100ml", "500ML+300ML"}; foreach (string str in strs) { var filteredStr=Regex.Replace(str,@"[^\d+*?\d+]", ""); MatchCollection ms = new Regex(@"(?<!.+)\d+|(?<=\+)\d+").Matches(filteredStr); int num = 0; foreach (Match r in ms) { num += int.Parse(r.Value); }; Response.Write(num+"<br/>");