我在将正则表达式匹配(基本上是字符串)转换为整数时遇到问题。
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);
}
}
}
}