【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, " "));
    }
}

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

相关文章
|
5月前
|
数据采集 机器学习/深度学习 大数据
行为检测代码(一):超详细介绍C3D架构训练+测试步骤
这篇文章详细介绍了C3D架构在行为检测领域的应用,包括训练和测试步骤,使用UCF101数据集进行演示。
160 1
行为检测代码(一):超详细介绍C3D架构训练+测试步骤
|
1月前
|
人工智能 自然语言处理 测试技术
Potpie.ai:比Copilot更狠!这个AI直接接管项目代码,自动Debug+测试+开发全搞定
Potpie.ai 是一个基于 AI 技术的开源平台,能够为代码库创建定制化的工程代理,自动化代码分析、测试和开发任务。
170 19
Potpie.ai:比Copilot更狠!这个AI直接接管项目代码,自动Debug+测试+开发全搞定
|
5月前
|
机器学习/深度学习 人工智能 监控
提升软件质量的关键路径:高效测试策略与实践在软件开发的宇宙中,每一行代码都如同星辰般璀璨,而将这些星辰编织成星系的过程,则依赖于严谨而高效的测试策略。本文将引领读者探索软件测试的奥秘,揭示如何通过精心设计的测试方案,不仅提升软件的性能与稳定性,还能加速产品上市的步伐,最终实现质量与效率的双重飞跃。
在软件工程的浩瀚星海中,测试不仅是发现缺陷的放大镜,更是保障软件质量的坚固防线。本文旨在探讨一种高效且创新的软件测试策略框架,它融合了传统方法的精髓与现代技术的突破,旨在为软件开发团队提供一套系统化、可执行性强的测试指引。我们将从测试规划的起点出发,沿着测试设计、执行、反馈再到持续优化的轨迹,逐步展开论述。每一步都强调实用性与前瞻性相结合,确保测试活动能够紧跟软件开发的步伐,及时适应变化,有效应对各种挑战。
|
5月前
|
缓存 C# Windows
C#程序如何编译成Native代码
【10月更文挑战第15天】在C#中,可以通过.NET Native和第三方工具(如Ngen.exe)将程序编译成Native代码,以提升性能和启动速度。.NET Native适用于UWP应用,而Ngen.exe则通过预编译托管程序集为本地机器代码来加速启动。不过,这些方法也可能增加编译时间和部署复杂度。
333 2
|
2月前
|
前端开发 JavaScript 测试技术
使用ChatGPT生成登录产品代码的测试用例和测试脚本
使用ChatGPT生成登录产品代码的测试用例和测试脚本
95 35
|
2月前
|
JavaScript 前端开发 Java
使用ChatGPT生成关于登录产品代码的单元测试代码
使用ChatGPT生成关于登录产品代码的单元测试代码
48 16
|
1月前
|
缓存 图形学
Unity C#for和foreach效率比较
该代码对比了三种遍历 `List&lt;int&gt;` 的方式的性能:使用缓存 `Count` 的 `for` 循环、每次访问 `list.Count` 的 `for` 循环以及 `foreach` 循环。通过 `Stopwatch` 测量每次遍历 300 万个元素所花费的时间,并输出结果。测试可在 Unity 环境中运行,按下空格键触发。结果显示,缓存 `Count` 的 `for` 循环性能最优,`foreach` 次之,而每次都访问 `list.Count` 的 `for` 循环最慢。
|
3月前
|
开发框架 .NET Java
C#集合数据去重的5种方式及其性能对比测试分析
C#集合数据去重的5种方式及其性能对比测试分析
45 11
|
3月前
|
算法 Java 测试技术
使用 BenchmarkDotNet 对 .NET 代码进行性能基准测试
使用 BenchmarkDotNet 对 .NET 代码进行性能基准测试
92 13
|
3月前
|
开发框架 .NET Java
C#集合数据去重的5种方式及其性能对比测试分析
C#集合数据去重的5种方式及其性能对比测试分析
62 10

热门文章

最新文章