C# 正则表达式去除字符串重复模式
使用正则表达式可以轻松判断字符串中是否有重复字符串模式,并将其去除。以下是 C# 代码示例:
using System.Text.RegularExpressions;
public static string RemoveDuplicateSubstring(string str)
{
string pattern = @"(.+)\1+";
Regex regex = new Regex(pattern);
Match match = regex.Match(str);
while (match.Success)
{
string duplicate = match.Groups[1].Value;
str = str.Replace(duplicate, "");
match = regex.Match(str);
}
return str;
}
该方法接收一个字符串参数,并返回去除重复字符串模式后的字符串。代码首先定义了一个正则表达式模式 (.+)\1+,它匹配任何包含重复子字符串的字符串。然后使用 Regex 类创建正则表达式对象并使用 Match 方法查找匹配项。循环遍历所有匹配项,获取重复的子字符串并使用 Replace 方法将其从原始字符串中删除。最后,返回处理后的字符串。
原文地址: https://www.cveoy.top/t/topic/oDnp 著作权归作者所有。请勿转载和采集!