如何将正则表达式匹配转换为整数?(返回"Input string was not in a correct format" )



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

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

    }
}

您应该使用:

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

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

已解决当我提取结果编号时,它大约是123456789,问题是数字之间的","。

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感谢所有回答的朋友:)

相关内容

最新更新