从字符串中删除已删除的字符

时间:2016-01-22 06:45:40

标签: c# regex string

我正在使用Regex从字符串中删除不需要的字符,如下所示:

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 = "☺,Å,ü,æ"

2 个答案:

答案 0 :(得分:2)

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);
    }
}

答案 1 :(得分:1)

以下示例说明如何使用评估程序Regex.Replace重载内使用回调方法执行此操作:

  

评估
  输入:System.Text.RegularExpressions.MatchEvaluator
  一种自定义方法,用于检查每个匹配并返回原始匹配字符串或替换字符串。

C#demo:

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 demo

简而言之,声明一个“全局”变量(字符串列表,这里是characters),将其初始化。添加Repl方法来处理替换,当Regex.Replace调用该方法时,将每个匹配的值添加到characters列表。