2010-12-16 11 views
17

不正な文字を削除する正規表現を探しています。しかし、私は文字がどうなるか分からない。例えば一致しない場合は文字を置換します。

:プロセスで

は、私は私の文字列が([a-zA-Z0-9/-]*)を一致させたいです。だから私はと一致しないすべての文字を上記の正規表現に置き換えたいと思います。だろう

+0

可能な複製http://stackoverflow.com/questions/3847294/replace-all-characters-not-in-range-java-string –

答えて

33

[^a-zA-Z0-9/-]+ 

[^ ]文字クラスの開始時には、それを否定する - それは、クラス内の文字をしませ一致します。

も参照してください:Kobiの答えにCharacter Classes

0

感謝を私はhelper method to strips unaccepted charactersを作成しました。

許可されているパターンは、正規表現形式である必要があります。角括弧で囲んでいることを前提としています。関数は、スクエアブラケットを開いた後にチルダを挿入します。 有効な文字セットを記述しているすべてのRegExでは動作しないことが予想されますが、使用している比較的シンプルなセットで動作します。

   /// <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; //returns result free of negated chars 
       } 
関連する問題