我在將正則表達式匹配(基本上是一個字符串)轉換爲整數時遇到問題。如何將正則表達式匹配轉換爲整數? (返回「輸入字符串的格式不正確」)
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。
我真的很困惑this.i嘗試了很多技巧,但沒有成功。 感謝幫助:)
編輯: 這裏是代碼:
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 + "https://stackoverflow.com/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);
}
}
}
}
把你想要一組中哪一個與拿到小組第一,而不是所有的朋友。 – Ryan
你的比賽似乎有非數字字符。他們看起來怎麼樣? – BlackBear
這是一個bing搜索結果,我想提取搜索結果的數量(它就像這個「12345結果」) –