检查NSString中的内容是否有一个带有正则表达式的模式



我有一个NSString,它将存储来自UITextField的数据,这些数据应该遵循一定的模式,这将是:

[0-9] / [0-9] / [0-9] 

在这种情况下,User类型的内容必须遵循此模式。我试着做这样的事情,但不工作:

if([myString  isEqual: @"[0-9]/[0-9]/[0-9]"]){
                       /* ...Others code here! */
}

我相信在Objective-C有一个特定的方式来处理正则表达式,我怎么能做到这一点?

谢谢。

假设您希望在斜杠周围允许可选的空格,就像您的[0-9] / [0-9] / [0-9]示例一样,这个正则表达式匹配您的模式:

^(?:[d-d]s*(?:/s*|$)){3}$

注意,在你的regex字符串中,你可能不得不用一个反斜杠转义每个反斜杠。

解释Regex

^                        # the beginning of the string
(?:                      # group, but do not capture (3 times):
  [                     #   '['
  d                     #   digits (0-9)
  -                      #   '-'
  d                     #   digits (0-9)
  ]                     #   ']'
  s*                    #   whitespace (n, r, t, f, and " ") (0
                         #   or more times (matching the most amount
                         #   possible))
  (?:                    #   group, but do not capture:
    /                    #     '/'
    s*                  #     whitespace (n, r, t, f, and " ")
                         #     (0 or more times (matching the most
                         #     amount possible))
   |                     #    OR
    $                    #     before an optional n, and the end of
                         #     the string
  )                      #   end of grouping
){3}                     # end of grouping
$                        # before an optional n, and the end of the
                         # string

最新更新