您的位置:首页 > 其它

.NET FRAMEWORK 正则表达式(例子)

2010-11-16 08:14 183 查看
private void button1_Click(object sender, EventArgs e)
{
string strDemo = "ABCDEFG";

long ticks = DateTime.Now.Ticks;

string strResult = "";

for (int i = 0; i < 50000; i++)
{
strResult += strDemo;
}

long interval = DateTime.Now.Ticks - ticks;

MessageBox.Show(interval.ToString() + " ticks");

}

private void button2_Click(object sender, EventArgs e)
{
string strDemo = "ABCDEFG";

long ticks = DateTime.Now.Ticks;

StringBuilder sb = new StringBuilder();

for (int i = 0; i < 50000; i++)
{
sb.Append( strDemo);
}

string strResult = sb.ToString();
long interval = DateTime.Now.Ticks - ticks;

MessageBox.Show(interval.ToString() + " ticks");

}

private void button3_Click(object sender, EventArgs e)
{
//匹配邮政编码
string s1 = @"/d{6}";

Regex rgx1 = new Regex(s1);

if (rgx1.IsMatch(this.textBoxInput.Text))
{
MessageBox.Show("输入串中包含邮政编码。");
}

//匹配非负整数
string s2 = @"^/d+$";

Regex rgx2 = new Regex(s2);

if (rgx2.IsMatch(this.textBoxInput.Text))
{
MessageBox.Show("输入串是一个非负整数");
}

//匹配正整数
string s3 = @"/+?0*[1-9]/d*";

Regex rgx3 = new Regex(s3);

MatchCollection matches = rgx3.Matches(this.textBoxInput.Text); //在输入串中搜索所有符合要求的子串

foreach (Match mth in matches)
{
MessageBox.Show(mth.Value);
}

//匹配整数
string s4 = @"[/+/-]?/d+";

//匹配三位小数
string s5 = @"[/+/-]?/d+/./d{3}";

//匹配整数或者1-3位小数
string s6 = @"[/+/-]?/d+(?:/./d{1,3})?";

//匹配所有以Tom开始的单词
string s7 = @"Tom[a-zA-Z]*/b";

Regex rgx7 = new Regex(s7, RegexOptions.IgnoreCase);

matches = rgx7.Matches(this.textBoxInput.Text);

foreach (Match mth in matches)
{
MessageBox.Show(mth.Value);
}

//匹配http url http://www.sina.com.cn:80/dir/test.html?p1=%ACDE&p2=%0235
string s8 = @"https?/:////[/w/-_]+(/.[/w/-_]+)*(/:/d{1,5})?(//[/w/-/._]*)*(/?[/w/%/+/=/&]+)?";

}

private void button4_Click(object sender, EventArgs e)
{
string s1 = @"^/d{6}$";

Regex rgx1 = new Regex(s1);

if (rgx1.IsMatch(this.textBoxInput.Text))
{
MessageBox.Show("输入串是一个邮政编码。");
}
}

private void button5_Click(object sender, EventArgs e)
{
string anchorPattern = @"/<a/s+(?:.*?)href=""(.*?)""(?:.*?)/>(.*?)/<//a/>";

Regex rgx = new Regex(anchorPattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);

System.IO.StreamReader reader = new System.IO.StreamReader("E://163.html");
string strContent = reader.ReadToEnd();

reader.Close();

MatchCollection matches = rgx.Matches(strContent);

foreach (Match mth in matches)
{
ListViewItem item = new ListViewItem(mth.Value);

string strAnchorHref = mth.Groups[1].Value;
string strAnchorText = mth.Groups[2].Value;

item.SubItems.Add(strAnchorText);
item.SubItems.Add(strAnchorHref);

this.listViewHyperLinks.Items.Add(item);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: