获取字符串中删除的字符
本文关键字:字符 删除 字符串 获取 | 更新日期: 2023-09-27 18:31:28
我正在使用正则表达式从字符串中删除不需要的字符,如下所示:
str = System.Text.RegularExpressions.Regex.Replace(str, @"[^'u0020-'u007E]", "");
如何检索将以有效方式删除的不同字符?
编辑:
Sample input : str = "This☺ contains Åüsome æspecialæ characters"
Sample output : str = "This contains some special characters"
removedchar = "☺,Å,ü,æ"
string pattern = @"['u0020-'u007E]";
Regex rgx = new Regex(pattern);
List<string> matches = new List<string> ();
foreach (Match match in rgx.Matches(str))
{
if (!matches.Contains (match.Value))
{
matches.Add (match.Value);
}
}
下面是
一个示例,如何使用计算器在Regex.Replace
重载中使用回调方法执行此操作:
计算器
类型:System.Text.RegularExpressions.MatchEvaluator
一种自定义方法,用于检查每个匹配项并返回原始匹配的字符串或替换字符串。
C# 演示:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class Test
{
public static List<string> characters = new List<string>();
public static void Main()
{
var str = Regex.Replace("§My string 123”˝", "[^'u0020-'u007E]", Repl);//""
Console.WriteLine(str); // => My string 123
Console.WriteLine(string.Join(", ", characters)); // => §, ”, ˝
}
public static string Repl(Match m)
{
characters.Add(m.Value);
return string.Empty;
}
}
查看 IDEONE 演示
简而言之,声明一个"全局"变量(字符串列表,此处,characters
),对其进行初始化。添加 Repl
方法以处理替换,当Regex.Replace
调用该方法时,将每个匹配的值添加到characters
列表中。