正则表达式匹配/替换指定字符串

版权声明:欢迎大家留言讨论共同进步,转载请注明出处 https://blog.csdn.net/qq_39108767/article/details/87190742
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;

public class Test : MonoBehaviour
{

    void Start()
    {
        string tStr = "abcdefgabcdeegabcdffg";
        string pStr = "d..g";
        string rStr = "****";

        string nStr = ReplaceMatchingStr(tStr, pStr, rStr, true);

        Debug.Log(tStr);
        Debug.Log(nStr);
        //输出结果: "abc****abc****abc****"
    }

    public string ReplaceMatchingStr(string targetStr, string patternStr, string replaceStr, bool isRecursion = true)
    {
        //targetStr: 待匹配字符串
        //patternStr: 正则表达式
        //isRecursion: 是否递归(查找所有/第一个符合表达式的字符串)

        //匹配表达式
        Regex regex = new Regex(patternStr);
        Match match = regex.Match(targetStr);

        //匹配结果
        return ReplaceMatchingStr(targetStr, match,replaceStr, isRecursion);
    }

    string ReplaceMatchingStr(string targetStr, Match match, string replaceStr, bool isRecursion)
    {
        //是否匹配成功
        if (match.Success)
        {
            //处理字符串
            targetStr = ReplaceStr(targetStr, match, replaceStr);

            //是否递归匹配
            if (isRecursion)
                targetStr = ReplaceMatchingStr(targetStr, match.NextMatch(), replaceStr, true);
        }
        return targetStr;
    }

    string ReplaceStr(string targetStr, Match match, string replaceStr)
    {
        //替换字符
        string newStr = targetStr.Replace(match.ToString(), replaceStr);

        ////匹配结果开始字符下标
        //Debug.Log(match.Index);
        ////匹配结果字符串长度
        //Debug.Log(match.Length);

        //Debug.Log(targetStr);
        //Debug.Log(newStr);

        return newStr;
    }

}

猜你喜欢

转载自blog.csdn.net/qq_39108767/article/details/87190742
今日推荐