user3613119
user3613119

Reputation: 91

Check if the content inside a NSString has a pattern with regex

I have a NSString that will store data coming from a UITextField, these data should follow a certain pattern that would be:

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

In this case the content that User type must follow this pattern. I try to do something like this, but doesn't work:

if([myString  isEqual: @"[0-9]/[0-9]/[0-9]"]){

                       /* ...Others code here! */
}

I believe in Objective-C Have a specific way to treat a regex, how can I be doing this?

Thanks.

Upvotes: 0

Views: 246

Answers (1)

zx81
zx81

Reputation: 41838

Assuming you want to allow optional spaces around the slashes as in your [0-9] / [0-9] / [0-9] example, this regex matches your pattern:

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

Note that in your regex string, you may have to escape each backslash with a backslash.

Explain 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

Upvotes: 1

Related Questions