日期:2014-05-17  浏览次数:20409 次

字符串相加
有如下字符串可能值为
5
10ml
20ML
120ml*4
360+120ML
360+100ml
500ML+300ML
如何转换对应为
5
10
20
120
480
460
800


------解决方案--------------------
下面可以将每行的数组提取出来,不过你要处理一下运算符号,乘除加减,或者你改用其他方法
C# code

            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+就可以了。
------解决方案--------------------
应该没什么简单的办法吧

C# code
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));
            }

------解决方案--------------------
C# code

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();
}

------解决方案--------------------
C# code

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/>");