0

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.

5
  • Isn't item #1, "Starts with \n or empty" useless? A string that starts with \n is nothing more than an empty line. Instead just search for the string you are looking for with an explicit '^' at the start of your regex. it will simplify the regex just a little bit. Commented Jan 27, 2013 at 21:50
  • @SlyRaskal Makes Sense, thanks. Do you know what's the problem with the rest? Commented Jan 27, 2013 at 21:52
  • Studying it now, don't know if what I'm coming up with will work though. Commented Jan 27, 2013 at 21:53
  • Could you post up some sample strings to test against? Commented Jan 27, 2013 at 21:57
  • I think you need to be more specific on what type of characters should be present when a # or * is at the end. I think that's the problem. Is it that there shouldn't be any numbers but it can be any other character if it ends with # or *? Commented Jan 27, 2013 at 22:05

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I was just about to answer the question myself. I got warning when I added one \. Objective-C requires you to add two \. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.