Регулярные выражения в ios(слово буква и специальные символы)

В приведенном ниже методе я хочу проверить текст UITextField, если: он содержит одно или несколько английских слов и одно или несколько чисел и пусть необязательно содержит специальные символы (!@$&#) возвращает true, иначе возвращает false.

#define pattern   @"^[a-zA-Z0-9\\u0021\\u0040\\u0023\\u0024\\u0026]{1}*$"

- (BOOL)stringHasCorrectFormat:(NSString *)str {

      if ([str componentsSeparatedByString:SPACE].count > 1)
         return NO;
      NSString *regularPattern = EMPTY_STRING;
      regularPattern = [regularPattern stringByAppendingString:pattern]
      NSRegularExpression *regex = [NSRegularExpression
                              regularExpressionWithPattern:regularPattern
                              options:NSRegularExpressionCaseInsensitive
                              error:nil];



      NSTextCheckingResult *match = [regex
                               firstMatchInString:str
                               options:0
                               range:NSMakeRange(0, [str length])];


     if (match != nil) {
         return YES;
     }

     return NO;
}

спасибо


person Mor4eza    schedule 28.05.2016    source источник
comment
в чем дело? вам нужно только показать слова или цифры?   -  person Iyyappan Ravi    schedule 28.05.2016
comment
На самом деле вы не разрешаете 0 или более символов. Используйте 1_. Если вы хотите убедиться, что есть буква и цифра, используйте @"^(?=[^a-zA-Z]*[a-zA-Z])(?=\\D*\\d)[a-zA-Z0-9\\u0021\\u0040\\u0023\\u0024\\u0026]*$"   -  person Wiktor Stribiżew    schedule 28.05.2016


Ответы (1)


Описание

^(?=.*[a-z])(?=.*[0-9])[a-z0-9!@$&#]*$

Визуализация регулярных выражений

Это регулярное выражение будет делать следующее:

  • (?=.*[a-z]) Требовать, чтобы строка содержала хотя бы один символ a-z
  • (?=.*[0-9]) Требовать, чтобы строка содержала хотя бы один символ 0-9
  • [a-z0-9!@$&#]*$ Разрешить строку состоять только из a-z символов, 0-9 символов и !@$&# символов

Пример

Текущая демонстрация

https://regex101.com/r/mC3kL3/1

Объяснение

NODE                     EXPLANATION
----------------------------------------------------------------------
  ^                        the beginning of a "line"
----------------------------------------------------------------------
  (?=                      look ahead to see if there is:
----------------------------------------------------------------------
    .*                       any character except \n (0 or more times
                             (matching the most amount possible))
----------------------------------------------------------------------
    [a-z]                    any character of: 'a' to 'z'
----------------------------------------------------------------------
  )                        end of look-ahead
----------------------------------------------------------------------
  (?=                      look ahead to see if there is:
----------------------------------------------------------------------
    .*                       any character except \n (0 or more times
                             (matching the most amount possible))
----------------------------------------------------------------------
    [0-9]                    any character of: '0' to '9'
----------------------------------------------------------------------
  )                        end of look-ahead
----------------------------------------------------------------------
  [a-z0-9!&#]*             any character of: 'a' to 'z', '0' to '9',
                           '!', '&', '#' (0 or more times (matching
                           the most amount possible))
----------------------------------------------------------------------
  $                        before an optional \n, and the end of a
                           "line"
----------------------------------------------------------------------
person Ro Yo Mi    schedule 28.05.2016