2010-12-16 62 views
17

我正在查找刪除非法字符的正則表達式。但我不知道角色會是什麼。如果不匹配,則替換字符

例如:

在一個過程中,我想我的字符串匹配([a-zA-Z0-9/-]*)。所以我想替換不匹配的所有字符上面的正則表達式。

+0

可能的重複http://stackoverflow.com/questions/3847294/replace-all-characters-not-in-range-java-string – 2012-08-30 14:30:04

回答

33

這將是:

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

[^ ]在字符類的開始否定它 - 它不是在類匹配的字符。

參見:Character Classes

0

由於Kobi的答案,我已經創建了一個helper method to strips unaccepted characters

允許的模式應該是正則表達式格式,期望它們被包裹在方括號中。打開squere括號後,函數將插入波形符號。 我預計它不能用於描述有效字符集的所有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 
       }