正则表达式之常用字符验证技巧

一:使用正则表达式检查字符串中重复出现的词,截图

二:代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ValidateWord
{
    public partial class Frm_Main : Form
    {
        public Frm_Main()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            /*
                
                    转义字符,将一个具有特殊功能的字符转义为一个普通字符,或反过来
                ^    匹配输入字符串的开始位置
                $    匹配输入字符串的结束位置
                *    匹配前面的零次或多次的子表达式
                +    匹配前面的一次或多次的子表达式
                ?    匹配前面的零次或一次的子表达式
                {n}    n是一个非负整数,匹配前面的n次子表达式
                {n,}    n是一个非负整数,至少匹配前面的n次子表达式
                {n,m}    m和n均为非负整数,其中n<=m,最少匹配n次且最多匹配m次
                ?    当该字符紧跟在其他限制符(*,+,?,{n},{n,},{n,m})后面时,
                匹配模式尽可能少的匹配所搜索的字符串
                .    匹配除“
”之外的任何单个字符
                (pattern)    匹配pattern并获取这一匹配
                (?:pattern)    匹配pattern但不获取匹配结果
                (?=pattern)    正向预查,在任何匹配pattern的字符串开始处匹配查找字符串
                (?!pattern)    负向预查,在任何不匹配pattern的字符串开始处匹配查找字符串
                x|y    匹配x或y。例如,‘z|food’能匹配“z”或“food”。‘(z|f)ood’则匹配“zood”或“food”
                [xyz]    字符集合。匹配所包含的任意一个字符。例如,‘[abc]’可以匹配“plain”中的‘a’
                [^xyz]    负值字符集合。匹配未包含的任意字符。例如,‘[^abc]’可以匹配“plain”中的‘p’
                [a-z]    匹配指定范围内的任意字符。例如,‘[a-z]’可以匹配'a'到'z'范围内的任意小写字母字符
                [^a-z]    匹配不在指定范围内的任意字符。例如,‘[^a-z]’可以匹配不在‘a’~‘z’'内的任意字符
                    匹配一个单词边界,指单词和空格间的位置
                B    匹配非单词边界
                d    匹配一个数字字符,等价于[0-9]
                D    匹配一个非数字字符,等价于[^0-9]
                f    匹配一个换页符
                
    匹配一个换行符
                
    匹配一个回车符
                s    匹配任何空白字符,包括空格、制表符、换页符等
                S    匹配任何非空白字符
                	    匹配一个制表符
                v    匹配一个垂直制表符。等价于x0b和cK
                w    匹配包括下划线的任何单词字符。等价于‘'[A-Za-z0-9_]’
                W    匹配任何非单词字符。等价于‘[^A-Za-z0-9_]’
                k<name>
                    命名后向引用。例如,(?<char>w)k<char> 查找双写的单词字符。表达式 (?<43>w)43 执行同样的操作。
                    可以使用单引号替代尖括号,例如 k'char'。
                (?<name>子表达式)
                    将匹配的子表达式捕获到一个组名称或编号名称中。用于 name 的字符串不得包含任何标点符号,
                    并且不能以数字开头。可以使用单引号替代尖括号,例如 (?'name')。
            
             */
            System.Text.RegularExpressions.MatchCollection matches =//使用正则表达式查找重复出现单词的集合
                System.Text.RegularExpressions.Regex.Matches(label1.Text,
                @"(?<word>w+)s+(k<word>)", System.Text.
                RegularExpressions.RegexOptions.Compiled | System.Text.
                RegularExpressions.RegexOptions.IgnoreCase);
            if (matches.Count != 0)//如果集合中有内容
            {
                foreach (System.Text.RegularExpressions.Match//遍历集合
                    match in matches)
                {
                    string word = match.Groups["word"].Value;//获取重复出现的单词
                    MessageBox.Show(word.ToString(), "英文单词");//弹出消息对话框
                }
            }
            else { MessageBox.Show("没有重复的单词"); }//弹出消息对话框
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            label1.Text =//创建字符串对象
                "The the quick brown fox  fox jumped over the lazy dog dog.";
        }
    }
}

三:使用正则表达式替换字符串,截图

四:代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ReplaceStr
{
    public partial class Frm_Main : Form
    {
        public Frm_Main()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            /*input
                类型:System.String
                要搜索匹配项的字符串。
                pattern
                类型:System.String
                要匹配的正则表达式模式。
                replacement
                类型:System.String
                替换字符串。
             */
            string strResult = System.Text.RegularExpressions.Regex.//使用正则表达式替换字符串
                Replace(textBox1.Text, @"[A-Za-z]*?", textBox2.Text);
            MessageBox.Show("替换前字符:" + "
" + textBox1.Text +//弹出消息对话框
                "
" + "替换的字符:" + "
" + textBox2.Text + "
" +
                "替换后的字符:" + "
" + strResult,"替换");
        }
        private void button2_Click(object sender, EventArgs e)
        {
            Close();//关闭窗体
        }
    }
}

五:使用正则表达式拆分字符串,截图

六:代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ValidateSplit
{
    public partial class Frm_Main : Form
    {
        public Frm_Main()
        {
            InitializeComponent();
        }

        private void btn_Split_Click(object sender, EventArgs e)
        {
            string[] P_Str = System.Text.RegularExpressions.//使用正则表达式根据数字进行拆分
                Regex.Split(txt_Split.Text, "[1-9]");
            foreach (string s in P_Str)//遍历拆分后的字符串集合
            {
                txt_Result.Text += s;//显示字符串
            }
        }

        private void btn_Close_Click(object sender, EventArgs e)
        {
            Application.Exit();//退出应用程序
        }
    }
}

七:使用正则表达式验证输入字母,截图

八:代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace IsLetter
{
    public partial class Frm_Main : Form
    {
        public Frm_Main()
        {
            InitializeComponent();
        }

        private void btn_Validate_Click(object sender, EventArgs e)
        {
            if (!IsLetter(textBox1.Text.Trim()))//验证字符串是否为大小写字母组成
            { MessageBox.Show("输入的不是字母!!!", "提示"); }//弹出消息对话框
            else { MessageBox.Show("输入的是字母!!!!!", "提示"); }//弹出消息对话框
        }

        /// <summary>
        /// 验证字符串是否为大小写字母组成
        /// </summary>
        /// <param name="str_Letter">字符串</param>
        /// <returns>方法返回布尔值</returns>
        public bool IsLetter(string str_Letter)
        {
            return System.Text.RegularExpressions.Regex.//使用正则表达式判断是否匹配
                IsMatch(str_Letter, @"^[A-Za-z]+$");
        }
    }
}

九:其他常见字符验证

使用正则表达式验证中文汉字输入    @"^[u4e00-u9fa5],{0,}$"

使用正则表达式验证输入字符串长度是否大于8         @"^.{8,}$"

使用正则表达式验证E-mail格式           @"^([w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$")

使用正则表达式验证IP地址             "(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)"

使用正则表达式验证URL             @"http(s)?://([w-]+.)+[w-]+(/[w- ./?%&=]*)?"

原文地址:https://www.cnblogs.com/hongmaju/p/3769911.html