-2

我在将正则表达式匹配(基本上是字符串)转换为整数时遇到问题。

Match results = Regex.Match(websr.ReadToEnd(),
                            "\\d+\\S+\\d+ results", RegexOptions.Singleline);
var count = Regex.Match(results.ToString(), "\\d+\\S+\\d+");

这两行是正则表达式。我想提取结果的数量。“count”显示正确的结果数。在下一步中,我想将其转换为整数类型

我尝试了{int countN = int.parse(count.ToString())}or{Int32.TryParse(count,out countN)}和许多其他情况,但"Input string was not in a correct format"在列表框中返回或显示 0。

我对此感到非常困惑。我尝试了很多技巧,但没有成功。感谢帮助 :)

编辑:这是代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Web;
using System.Net;
using System.Text.RegularExpressions;
using System.IO;

namespace bing
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            CookieCollection cookies = new CookieCollection();

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.bing.com/");
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.Add(cookies);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader response1 = new StreamReader(response.GetResponseStream());
            cookies = response.Cookies;

            try
            {
                string web = "http://www.bing.com";
                //post
                string getUrl = (web + "/search?q=" + textBox1.Text);


                HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(getUrl);
                HttpWebResponse webrep = (HttpWebResponse)webreq.GetResponse();
                StreamReader websr = new StreamReader(webrep.GetResponseStream());
                Match results = Regex.Match(websr.ReadToEnd(), "\\d+\\S+\\d+ results", RegexOptions.Singleline);
                var count = Regex.Match(results.ToString(), "\\d+\\S+\\d+");
                int countN = int.Parse(count.Value);



                listBox1.Items.Add(countN.ToString());
            }

            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }
        }


    }
}
4

2 回答 2

0

当我提取结果编号时解决了,它类似于 123,456,789,问题是数字之间的“,”。

Match results = Regex.Match(websr.ReadToEnd(), "\\d+\\S+\\d+ results", RegexOptions.Singleline);
Match count = Regex.Match(results.ToString(), "\\d+\\S+\\d+");

string countN = count.Value.Replace(",", "");
int countM = int.Parse(countN);

和 countM 显示 123456789 感谢所有回答的朋友:)

于 2013-08-26T04:57:53.687 回答
0

你应该使用:

var count = int.Parse(Regex.Match(results.ToString(), "\\d+\\S+\\d+").Value);

验证输入字符串中只有数字。

于 2013-08-25T16:08:32.260 回答