2010-12-16 3 views
17

Я ищу регулярное выражение, которое удаляет незаконные символы. Но я не знаю, какими будут персонажи.Заменить символы, если они не соответствуют

Например:

В процессе, я хочу, чтобы моя строка соответствовала ([a-zA-Z0-9/-]*). Поэтому я хотел бы заменить все символы, которые не соответствуют regexp выше.

+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 «s Я создал helper method to strips unaccepted characters.

Разрешенный шаблон должен быть в формате Regex, ожидайте, что они завернуты в квадратные скобки. Функция будет вставлять тильду после открытия скобки скребка. Я ожидаю, что он может работать не для всех 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 
       } 
Смежные вопросы