【C#】正则表达式匹配替换指定字符串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;
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。