一个网页的源代码里包括下面的一段代码:
<span name="code" width="65px" style="background:#CCC;font-size:14px">&nbsp;8+4=?其他的内容可以忽略,现在我想用正则表达式找到最后面的那个算术表达式的内容,然后计算结果。
因为对正则表达式还不是很熟,所以想问下大家觉得应该怎样设计这个正则呢。注意算术表达式里的符号只有三种:+  - x  对,是x而不是*。例如我想获得的是5x8        9-4        65+5      等等这类的结果。先谢谢。

解决方案 »

  1.   

    如果在固定的span里,那么就用找到span的特点用正则过滤出来。
      

  2.   

    var regex = /\d+[+\-x]\d+/
    var str = '<span name="code" width="65px" style="background:#CCC;font-size:14px">&nbsp;8+4 &nbsp;</span>';
    str = str.replace(regex,function(w)
    {
        return eval(w.replace(/x/,"*"));
    })
    alert(str)
      

  3.   


    void Main()
    {
    string html=@"<span name=""code"" width=""65px"" style=""background:#CCC;font-size:14px"">&nbsp;8+4=?
    ";
       foreach(Match m in Regex.Matches(html,@"(?is)<span[^>]*?>.*?(\d+[+\-x]\d+)"))
       {
        string temp=m.Groups[1].Value;
     if(!string.IsNullOrEmpty(temp))
     {
            Console.WriteLine("{0} = {1}",temp,new DataTable().Compute(temp.Replace("x","*"),null));
         }
       }
       //8+4 = 12
    }
      

  4.   


    你好,你的回答让我有点思路了。不过想再问下一开始我如何在全部的文本信息里获取到
    <span name=""code"" width=""65px"" style=""background:#CCC;font-size:14px"">&nbsp;8+4=? 呢。我得先获取到这一段文本再按照你的这种方法来获取结果对吗。
      

  5.   


    void Main()
    {
    string html=@"<span name=""code"" width=""65px"" style=""background:#CCC;font-size:14px"">&nbsp;8x4=?
    ";
       foreach(Match m in Regex.Matches(html,@"(?i)(?<=<span[^>]*?>\D+)\d+[+\-x]\d+(?=\=\?)"))
       {
    string temp=m.Value;
     if(!string.IsNullOrEmpty(temp))
     {
    Console.WriteLine("{0} = {1}",temp,new DataTable().Compute(temp.Replace("x","*"),null));
    }
       }
       //8x4 = 32
    }