2010-12-16 22 views
17

Estoy buscando una expresión regular que elimine caracteres ilegales. Pero no sé cuáles serán los personajes.Reemplazar caracteres si no coincide

Por ejemplo:

En un proceso, yo quiero que mi cadena para que coincida con ([a-zA-Z0-9/-]*). Así que me gustaría reemplazar todos los caracteres que no coincidan con la expresión regular anterior.

+0

Posible duplicado de http://stackoverflow.com/questions/3847294/replace-all-characters-not-in-range-java-string –

Respuesta

33

Eso sería:

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

[^ ] en el inicio de una clase de caracteres lo niega - que coincide con caracteres no en la clase.

Consulte también: Character Classes

0

Gracias a la respuesta Kobi 's He creado un helper method to strips unaccepted characters.

El patrón permitido debe estar en formato Regex, espere que estén entre corchetes. Una función insertará una tilde después de abrir el soporte de squere. Anticipo que podría funcionar no para todos los RegEx que describen conjuntos de caracteres válidos, pero funciona para conjuntos relativamente simples, que estamos usando.

   /// <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 
       } 
Cuestiones relacionadas