Jensen
Jensen

Reputation: 1723

regex pattern to match string in Objective C

Here is a regex pattern I created in Objective C:

^\n?([#]{1,2}$|[*]{1,2}$|[0-9]{1,3}.$)

I want to match:

  1. starts with \n or empty
  2. ends with # or * or .
  3. if ends with . there will be 1 or 2 or 3 digits in between
  4. If ends with # or *, there could be 1 more # or * in between

The regex I created matches '\n1#' which is not what I want. Can anyone help me correct this? Is this fastest one? The regex will be used frequently, so I want it to be as fast as possible.

UPDATE:

Here's a sample strings for testing:

"\n#", "11*1", "1#", "a1.", "111*", "\n1#", "\n11.", "a11.", "1. ", "*1."

The 1# and 111* were matched. Not sure what went wrong.

Upvotes: 0

Views: 1314

Answers (1)

Jilouc
Jilouc

Reputation: 12714

You're matching #1 and 111# because of [0-9]{1,3}.. You haven't escaped the . and this group basically matches any sequence of 1 to 3 digits followed by any character.

What you're looking for is

^\n?(#{1,2}|\*{1,2}|[0-9]{1,3}\.)$

Properly escaped in ObjC, it would be

@"^\n?(#{1,2}|\\*{1,2}|[0-9]{1,3}\\.)$"

If this regex is used quite a lot, you might want to cache the NSRegularExpression object to avoid compiling it everytime.

Regexpal is very useful to test regular expressions.

Upvotes: 1

Related Questions