19

文字列を検証するための正規表現があります。しかし、今度は、正規表現に一致しないすべての文字を削除したいと思います。

例えば

regExpression = @"^([\w\'\-\+])"

text = "This is a sample text with some invalid characters -+%&()=?";

//Remove characters that do not match regExp.

result = "This is a sample text with some invalid characters -+";

正規表現を使用して有効な文字を判別し、他のすべての文字を削除する方法についてのアイデア。

どうもありがとう

4

3 に答える 3

19

これ(文字をホワイトリストに登録し、他のすべてを置き換える)を1行で実行できると思います。

var result = Regex.Replace(text, @"[^\w\s\-\+]", "");

技術的には、次のように生成されます。「これは、いくつかの無効な文字-+を含むサンプルテキストです」これは、例とは少し異なります(-と+の間の余分なスペース)。

于 2011-05-27T15:40:34.617 に答える
15

そのような単純な:

var match = Regex.Match(text, regExpression);
string result = "";
if(match.Success)
    result = match.Value;

一致しない文字を削除することは、一致する文字を保持することと同じです。それが私たちがここで行っていることです。

式がテキスト内で複数回一致する可能性がある場合は、次を使用できます。

var result = Regex.Matches(text, regExpression).Cast<Match>()
                  .Aggregate("", (s, e) => s + e.Value, s => s);
于 2011-05-27T15:29:57.540 に答える
3

回答に一致しない場合は文字を置換してください。受け入れられない文字を削除するヘルパーメソッドを作成しました。

許可されるパターンは正規表現形式である必要があり、角かっこで囲まれている必要があります。関数は、スクワイアブラケットを開いた後にチルダを挿入します。有効な文字セットを記述するすべての正規表現では機能しないと思いますが、使用している比較的単純なセットでは機能します。

 /// <summary>
               /// Replaces  not expected characters.
               /// </summary>
               /// <param name="text"> The text.</param>
               /// <param name="allowedPattern"> The allowed pattern in Regex format, expect them wrapped in brackets</param>
               /// <param name="replacement"> The replacement.</param>
               /// <returns></returns>
               /// //        https://stackoverflow.com/questions/4460290/replace-chars-if-not-match.
               //https://stackoverflow.com/questions/6154426/replace-remove-characters-that-do-not-match-the-regular-expression-net
               //[^ ] at the start of a character class negates it - it matches characters not in the class.
               //Replace/Remove characters that do not match the Regular Expression
               static public string ReplaceNotExpectedCharacters( this string text, string allowedPattern,string replacement )
              {
                     allowedPattern = allowedPattern.StripBrackets( "[", "]" );
                      //[^ ] at the start of a character class negates it - it matches characters not in the class.
                      var result = Regex .Replace(text, @"[^" + allowedPattern + "]", replacement);
                      return result;
              }

static public string RemoveNonAlphanumericCharacters( this string text)
              {
                      var result = text.ReplaceNotExpectedCharacters(NonAlphaNumericCharacters, "" );
                      return result;
              }
        public const string NonAlphaNumericCharacters = "[a-zA-Z0-9]";

ここで使用されているStringHelperクラス http://geekswithblogs.net/mnf/archive/2006/07/13/84942.aspxの関数がいくつかあります。

           /// <summary>
           /// ‘StripBrackets checks that starts from sStart and ends with sEnd (case sensitive).
           ///           ‘If yes, than removes sStart and sEnd.
           ///           ‘Otherwise returns full string unchanges
           ///           ‘See also MidBetween
           /// </summary>

           public static string StripBrackets( this string str, string sStart, string sEnd)
          {
                  if (CheckBrackets(str, sStart, sEnd))
                 {
                       str = str.Substring(sStart.Length, (str.Length – sStart.Length) – sEnd.Length);
                 }
                  return str;
          }
           public static bool CheckBrackets( string str, string sStart, string sEnd)
          {
                  bool flag1 = (str != null ) && (str.StartsWith(sStart) && str.EndsWith(sEnd));
                  return flag1;
          }
于 2012-10-28T02:50:01.173 に答える