C#从字符串中提取所有的数字并获得数字个数(正则表达式)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Collections;
namespace 提取数字
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static bool IsNumber(string s)
{
const string pattern = @"\d^]";
Regex rx = new Regex(pattern);
return rx.IsMatch(s);
}
private void button1_Click(object sender, EventArgs e)
{
string str = "ssdwq=1111111]dq=117549847580=11790]";
string num = "";
bool ha = false;
ArrayList fig = new ArrayList();
for (int i = 0; i < str.Length; i++)
{
if (IsNumber(str[i].ToString()))
{
num += str[i];
ha = true;
}
else
{
if (ha)
{
fig.Add(long.Parse(num));
num = "";
ha = false;
}
}
}
//显示出来
string show = "";
for (int i = 0; i < fig.Count; i++)
{
show += fig[i] + ",";
}
MessageBox.Show("数据数量:" + fig.Count + "\r 分别为:" + show);
}
}
}
在winform中,只需要添加一个button按钮即可。