看範例學C#-18 Regular Expression 規則運算式

  • 19210
  • 0
  • C#
  • 2012-10-07

看範例學C#-18 Regular Expression 規則運算式

規則運算式可以很容易的幫我們分析、比對字串,實在是很強大的一個功能

要使用規則運算式需(Regular Expression)在程式開頭 using System.Text.RegularExpressions;

本範例使用isright(string s, String right) 來比對 字串 跟運算式是否相符

符合的話傳回true,否則傳回false

想更了解規則運算式語法可以參考以下三篇文章

http://msdn.microsoft.com/zh-tw/library/ae5bf541

http://www.dotblogs.com.tw/johnny/archive/2010/01/25/13301.aspx#24159

http://www.dotblogs.com.tw/johnny/archive/2010/03/02/13855.aspx

 

以下為本例原始碼


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;
namespace ex18
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.AcceptButton = button1;//按下enter就觸發button click事件
        }
        private void button1_Click(object sender, EventArgs e)
        {
            txtEmail.Text = txtEmail.Text.Trim();
            if (isright(txtEmail.Text, @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"))//符合運算式
            {
                errorProvider1.SetError(txtEmail, "");
                MessageBox.Show("有效的電子信箱");
            }
            else
            {
                errorProvider1.SetError(txtEmail, "輸入的電子信箱不正確");
            }
        }
        public Boolean isright(string s, String right) //定義正則表達式函數
        {
            Regex Regex1 = new Regex(right, RegexOptions.IgnoreCase);
            return Regex1.IsMatch(s);
        }
    }
}


ex18.rar
 


如有錯誤 歡迎指正