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

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

相关文章
|
3月前
|
测试技术 开发者 Python
Python单元测试入门:3个核心断言方法,帮你快速定位代码bug
本文介绍Python单元测试基础,详解`unittest`框架中的三大核心断言方法:`assertEqual`验证值相等,`assertTrue`和`assertFalse`判断条件真假。通过实例演示其用法,帮助开发者自动化检测代码逻辑,提升测试效率与可靠性。
373 1
|
4月前
|
算法 IDE Java
Java 项目实战之实际代码实现与测试调试全过程详解
本文详细讲解了Java项目的实战开发流程,涵盖项目创建、代码实现(如计算器与汉诺塔问题)、单元测试(使用JUnit)及调试技巧(如断点调试与异常排查),帮助开发者掌握从编码到测试调试的完整技能,提升Java开发实战能力。
477 0
|
2月前
|
安全 Java 测试技术
《深入理解Spring》单元测试——高质量代码的守护神
Spring测试框架提供全面的单元与集成测试支持,通过`@SpringBootTest`、`@WebMvcTest`等注解实现分层测试,结合Mockito、Testcontainers和Jacoco,保障代码质量,提升开发效率与系统稳定性。
|
3月前
|
人工智能 边缘计算 搜索推荐
AI产品测试学习路径全解析:从业务场景到代码实践
本文深入解析AI测试的核心技能与学习路径,涵盖业务理解、模型指标计算与性能测试三大阶段,助力掌握分类、推荐系统、计算机视觉等多场景测试方法,提升AI产品质量保障能力。
|
5月前
|
安全 Java 测试技术
Java 项目实战中现代技术栈下代码实现与测试调试的完整流程
本文介绍基于Java 17和Spring技术栈的现代化项目开发实践。项目采用Gradle构建工具,实现模块化DDD分层架构,结合Spring WebFlux开发响应式API,并应用Record、Sealed Class等新特性。测试策略涵盖JUnit单元测试和Testcontainers集成测试,通过JFR和OpenTelemetry实现性能监控。部署阶段采用Docker容器化和Kubernetes编排,同时展示异步处理和反应式编程的性能优化。整套方案体现了现代Java开发的最佳实践,包括代码实现、测试调试
221 0
|
6月前
|
测试技术 Go 开发者
如何为 gRPC Server 编写本地测试代码
本文介绍了如何使用 Go 语言中的 gRPC 测试工具 **bufconn**,通过内存连接实现 gRPC Server 的本地测试,避免端口冲突和外部依赖。结合示例代码,讲解了初始化内存监听、自定义拨号器及编写测试用例的完整流程,并借助断言库提升测试可读性与准确性。适用于单元及集成测试,助力高效开发。
139 1
|
8月前
|
存储 jenkins 测试技术
Apipost自动化测试:零代码!3步搞定!
传统手动测试耗时低效且易遗漏,全球Top 10科技公司中90%已转向自动化测试。Apipost无需代码,三步实现全流程自动化测试,支持小白快速上手。功能涵盖接口测试、性能压测与数据驱动,并提供动态数据提取、CICD集成等优势,助力高效测试全场景覆盖。通过拖拽编排、一键CLI生成,无缝对接Jenkins、GitHub Actions,提升测试效率与准确性。
678 11
|
8月前
|
人工智能 自然语言处理 测试技术
自然语言生成代码一键搞定!Codex CLI:OpenAI开源终端AI编程助手,代码重构+测试全自动
Codex CLI是OpenAI推出的轻量级AI编程智能体,基于自然语言指令帮助开发者高效生成代码、执行文件操作和进行版本控制,支持代码生成、重构、测试及数据库迁移等功能。
1715 0
自然语言生成代码一键搞定!Codex CLI:OpenAI开源终端AI编程助手,代码重构+测试全自动
|
10月前
|
人工智能 自然语言处理 测试技术
Potpie.ai:比Copilot更狠!这个AI直接接管项目代码,自动Debug+测试+开发全搞定
Potpie.ai 是一个基于 AI 技术的开源平台,能够为代码库创建定制化的工程代理,自动化代码分析、测试和开发任务。
901 19
Potpie.ai:比Copilot更狠!这个AI直接接管项目代码,自动Debug+测试+开发全搞定