【Unity 3D】C#中正则表达式的详解(附测试代码 超详细)

简介: 【Unity 3D】C#中正则表达式的详解(附测试代码 超详细)

正则表达式,又称规则表达式,在代码中常简写为regex、regexp,常用来检索替换那些符合某种模式的文本

1:匹配正整数

下面的代码演示了在Unity 3D中应用正则表达式检查文本是否是正整数

using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test_12_1 : MonoBehaviour
{
    void Start()
    {
        string temp = "123";
        Debug.Log(IsNumber(temp));
    }
    ///<summary> 
    ///匹配正整数
    ///</summary> 
    ///<param name="strInput"></param>
    ///<returns></returns>
    public bool IsNumber(string strInput)
    {
        Regex reg = new Regex("^[0-9]*[1-9][0-9]*$");
        if (reg.IsMatch(strInput))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

2:匹配大写字母

还可以应用正则表达式匹配大写字母,检查文本是否都是大写字母

using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test_12_2 : MonoBehaviour
{
    void Start()
    {
        string temp = "ABC";
        Debug.Log(IsCapital(temp));
    }
    ///<summary>
    ///匹配由26个英文字母的大写组成的字符串
    ///</summary>
    ///<param name="strInput"></param>
    ///<returns></returns>
    public bool IsCapital(string strInput)
    {
        Regex reg = new Regex("^[A-Z]+$");
        if (reg.IsMatch(strInput))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

3:Regex类

正则表达式是一种文本模式,包括普通字符和特殊字符,正则表达式使用单个字符描述一系列匹配某个句法规则的字符串 常用方法如下

IsMatch() 判断正则表达式是否在指定输入字符串中找到匹配项

MatchCollection() 在指定的输入字符串中搜索正则表达式的所有匹配项

Replace() 在指定的输入字符串中,把匹配的正则表达式的所有字符串替换为指定的字符串

Split() 把输入字符串分割为子字符串数组

静态Match方法实例代码如下

using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test_12_3 : MonoBehaviour
{
    void Start()
    {
        string temp = "aaaa(bbb)aaaaaaaaa(bb)aaaaaa";
        IsMatch(temp);
    }
    ///<summary>
    ///在输入的字符串中搜索正则表达式的匹配项
    ///</summary>
    ///<param name="strInput">输入的字符串</param>
    public void IsMatch(string strInput)
    {
        string pattern = "\\(\\w+\\)";
        Match result = Regex.Match(strInput, pattern);
        Debug.Log("第一种重载方法:"+result.Value);
        Match result2 = Regex.Match(strInput, pattern,RegexOptions.RightToLeft);
        Debug.Log("第二种重载方法:" + result2.Value);
    }
}

静态Matches方法,它返回所有匹配项的集合

using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test_12_4 : MonoBehaviour
{
    void Start()
    {
        string temp = "aaaa(bbb)aaaaaaaaa(bb)aaaaaa";
        IsCapital(temp);
    }
    ///<summary>
    ///在输入的字符串中搜索正则表达式的匹配项
    ///</summary>
    ///<param name="strInput">输入的字符串</param>
    public void IsCapital(string strInput)
    {
        string pattern = "\\(\\w+\\)";
        MatchCollection results = Regex.Matches(strInput, pattern);
        for (int i = 0; i < results.Count; i++)
        {
            Debug.Log("第一种重载方法:" + results[i].Value);
        }
        MatchCollection results2 = Regex.Matches(strInput, pattern,RegexOptions.RightToLeft);
        for (int i = 0; i < results.Count; i++)
        {
            Debug.Log("第二种重载方法:" + results2[i].Value);
        }
    }
}

IsMatch方法,在输入的字符串中使用正则表达式搜索匹配项,找到返回true,没找到则返回false

using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test_12_5 : MonoBehaviour
{
    void Start()
    {
        string temp = "aaaa(bbb)aaaaaaaaa(bb)aaaaaa";
        IsMatch(temp);
    }
    ///<summary>
    ///在输入的字符串中搜索正则表达式的匹配项
    ///</summary>
    ///<param name="strInput">输入的字符串</param>
    public void IsMatch(string strInput)
    {
        string pattern = "\\(\\w+\\)";
        bool resultBool = Regex.IsMatch(strInput, pattern);
        Debug.Log(resultBool);
        bool resultBool2 = Regex.IsMatch(strInput, pattern,RegexOptions.RightToLeft);
        Debug.Log(resultBool2);
    }
}

4:定义正则表达式

转义字符

正则表达式中的反斜杠字符\是指其后跟的是特殊字符,或者应该按原义解释该字符

测试代码如下

using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test_12_6 : MonoBehaviour
{
    void Start()
    {
        string temp = "\r\nHello\nWorld.";
        IsMatch(temp);
    }
    ///<summary>
    ///在输入的字符串中搜索正则表达式的匹配项
    ///</summary>
    ///<param name="strInput">输入的字符串</param>
    public void IsMatch(string strInput)
    {
        string pattern = "\\r\\n(\\w+)";
        Match resultBool = Regex.Match(strInput, pattern);
        Debug.Log(resultBool.Value);
    }
}

字符类

正则表达式中的字符类可以与一组字符中的任何一个字符匹配,如使用\r时可以加上\w,这样就可以匹配换行后的所有单词字符

using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test_12_7 : MonoBehaviour
{
    void Start()
    {
        string temp = "Hello World 2020";
        IsMatch(temp);
    }
    ///<summary>
    ///在输入的字符串中搜索正则表达式的匹配项
    ///</summary>
    ///<param name="strInput">输入的字符串</param>
    public void IsMatch(string strInput)
    {
        string pattern = "(\\d+)";
        Match resultBool = Regex.Match(strInput, pattern);
        Debug.Log(resultBool.Value);
    }
}

定位点

正则表达式中的定位点可以设置匹配字符串的索引位置,所以可以使用定位点对要匹配的字符进行限定,以此得到想要匹配到的字符串

using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test_12_8 : MonoBehaviour
{
    void Start()
    {
        string temp = "Hello World 2020";
        IsMatch(temp);
    }
    ///<summary>
    ///在输入的字符串中搜索正则表达式的匹配项
    ///</summary>
    ///<param name="strInput">输入的字符串</param>
    public void IsMatch(string strInput)
    {
        string pattern = "(\\w+)$";
        Match resultBool = Regex.Match(strInput, pattern);
        Debug.Log(resultBool.Value);
    }
}

限定符

正则表达式中的限定符指定在输入字符串中必须存在上一个元素的多少个实例才能出现匹配项

* 匹配上一个元素0次或多次

+ 匹配上一个元素1次或者多次

? 匹配上一个元素0次或者1次

{n} 匹配上一个元素n次

{n,m} 匹配上一个元素最少n次,最多m次

测试代码如下

using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test_12_9 : MonoBehaviour
{
    void Start()
    {
        string temp = "Hello World";
        IsMatch(temp);
    }
    ///<summary>
    ///在输入的字符串中搜索正则表达式的匹配项
    ///</summary>
    ///<param name="strInput">输入的字符串</param>
    public void IsMatch(string strInput)
    {
        string pattern = "\\w{5}";
        Match resultBool = Regex.Match(strInput, pattern);
        Debug.Log(resultBool.Value);
    }
}

5:常用正则表达式

正则表达式很强大,可以匹配各种类型的字符串,如大写字母 小写字母 正整数 负正整数 汉字 email地址 电话号码和身份证号码等等  下面列出一些常用的正则表达式

常用校验数字的表达式

using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test_12_10 : MonoBehaviour
{
    void Start()
    {
        string temp = "2020";
        IsMatch(temp);
    }
    ///<summary>
    ///在输入的字符串中搜索正则表达式的匹配项
    ///</summary>
    ///<param name="strInput">输入的字符串</param>
    public void IsMatch(string strInput)
    {
        Regex reg = new Regex(@"^[0-9]*$");
        bool result = reg.IsMatch(strInput);
        Debug.Log(result);
    }
}

校验字符的表达式

字符包含汉字 英文 数字以及特殊符号时,使用正则表达式可以很方便的将这些字符匹配出来

using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test_12_11 : MonoBehaviour
{
    void Start()
    {
        string temp = "你好,世界 2020";
        IsMatch(temp);
    }
    ///<summary>
    ///在输入的字符串中搜索正则表达式的匹配项
    ///</summary>
    ///<param name="strInput">输入的字符串</param>
    public void IsMatch(string strInput)
    {
        Regex reg = new Regex(@"^[\u4E00-\u9FA5A-Za-z0-9]");
        bool result = reg.IsMatch(strInput);
        Debug.Log("匹配中文、英文和数字:" + result);
        Regex reg2 = new Regex(@"^[A-Za-z0-9]");
        bool result2 = reg2.IsMatch(strInput);
        Debug.Log("匹配英文和数字:" + result2);
    }
}

校验特殊需求的表达式

using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test_12_12 : MonoBehaviour
{
    void Start()
    {
        IsMatch();
    }
    ///<summary>
    ///在输入的字符串中搜索正则表达式的匹配项
    ///</summary>
    ///<param name="strInput">输入的字符串</param>
    public void IsMatch()
    {
        Regex reg = new Regex(@"[a-zA-z]+://[^\s]*");
        bool result = reg.IsMatch("http://www.baidu.com");
        Debug.Log("匹配网址:" + result);
        Regex reg2 = new Regex(@"^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$");
        bool result2 = reg2.IsMatch("13512341234");
        Debug.Log("匹配手机号码:" + result2);
    }
}

6:正则表达式实例

实例一:匹配字母

在开发中常常遇到要找到以某个字母开头或者某个字母结尾的单词  代码如下

下面使用正则表达式匹配以m开头,以e结尾的单词

using System.Text.RegularExpressions;
using UnityEngine;
public class Test_12_13 : MonoBehaviour
{
    void Start()
    {
        string temp = "make maze and manage to measure it";
        MatchStr(temp);
    }
    ///<summary>
    ///在输入的字符串中搜索正则表达式的匹配项
    ///</summary>
    ///<param name="strInput">输入的字符串</param>
    public void MatchStr(string str)
    {
        Regex reg = new Regex(@"\bm\S*e\b");
        MatchCollection mat = reg.Matches(str);
        foreach (Match item in mat)
        {
            Debug.Log(item);
        }
    }
}

实例二:替换掉空格

在数据传输中,可能会在无意间添加多个空格,这会影响解析 下面演示如何去掉多余的空格

using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test_12_14 : MonoBehaviour
{
    void Start()
    {
        string temp = "Hello              World";
        MatchStr(temp);
    }
    ///<summary>
    ///在输入的字符串中搜索正则表达式的匹配项
    ///</summary>
    ///<param name="strInput">输入的字符串</param>
    public void MatchStr(string str)
    {
        Regex reg = new Regex("\\s+");
        Debug.Log(reg.Replace(str, " "));
    }
}

创作不易 觉得有帮助请点赞关注收藏~~~

相关文章
|
1月前
|
Java 关系型数据库 数据库连接
Mybatis+MySQL动态分页查询数据经典案例(含代码以及测试)
Mybatis+MySQL动态分页查询数据经典案例(含代码以及测试)
28 1
|
1月前
|
C# Windows
C#通过代码实现快捷键编辑
C#通过代码实现快捷键编辑
|
2月前
|
测试技术
包含用例执行时间的测试报告代码
包含用例执行时间的测试报告代码
|
3月前
|
开发框架 .NET 编译器
C# 10.0中Lambda表达式的改进:更简洁、更灵活的代码编写体验
【1月更文挑战第21天】随着C#语言的不断发展,Lambda表达式作为一种简洁、高效的函数式编程工具,在C# 10.0中迎来了重要的改进。本文将详细探讨C# 10.0中Lambda表达式的新特性,包括参数类型的推断增强、自然类型的Lambda参数以及Lambda表达式的属性改进等。这些改进不仅简化了Lambda表达式的编写过程,还提升了代码的可读性和灵活性,为开发者带来了更优质的编程体验。
|
3月前
|
C# 开发者
C# 10.0中的文件范围命名空间:简化代码组织的新方式
【1月更文挑战第18天】C# 10.0引入了文件范围的命名空间,这是一种新的语法糖,用于更简洁地组织和管理代码。文件范围命名空间允许开发者在每个文件的基础上定义命名空间,而无需显式使用花括号包裹整个文件内容。本文将深入探讨文件范围命名空间的工作原理、使用场景以及它们为C#开发者带来的便利。
|
10天前
|
图形学 C++
【Unity Shader入坑篇---有ASE创建Unity Shader,那么Unity Shader代码的相关知识还有必要学或了解吗?】
【Unity Shader入坑篇---有ASE创建Unity Shader,那么Unity Shader代码的相关知识还有必要学或了解吗?】
|
18天前
|
算法 安全 Java
java代码 实现AES_CMAC 算法测试
该代码实现了一个AES-CMAC算法的简单测试,使用Bouncy Castle作为安全提供者。静态变量K定义了固定密钥。`Aes_Cmac`函数接受密钥和消息,返回AES-CMAC生成的MAC值。在`main`方法中,程序对给定的消息进行AES-CMAC加密,然后模拟接收ECU的加密结果并进行比较。如果两者匹配,输出&quot;验证成功&quot;,否则输出&quot;验证失败&quot;。辅助方法包括将字节转为16进制字符串和将16进制字符串转为字节。
|
1月前
|
测试技术 数据库 Python
python测试代码(二)
python测试代码(二)
19 0
|
1月前
|
开发框架 .NET 编译器
C#学习相关系列之匿名方法和Lambda表达式
C#学习相关系列之匿名方法和Lambda表达式
|
1月前
|
Java 测试技术
单元测试编写可测试代码
单元测试编写可测试代码
19 2