0
//string
NSString *haystack = @".test {test:test} .test2{dasf:asdF}";
//pattern
 NSString *needle = @"[^{}]*{[^{}]*}";

What I want from this is .test {test:test} and .test2{dasf:asdF} in an array (rest of the code handles this) but for some reason this regexp is not working correctly because no results are found.

If

NSString *needle = @"[^{}]*";

I get the following

(
".test ",
"",
"test:test",
"",
" .test2",
"",
"dasf:asdF",
"",
""
)

which is expected. After a lot of fiddling it seems to be a problem with { and } in the regex but I can't think why.

Incidently, if anyone can explain why I get these empty elements in the array above that would be useful to know as well.

Thanks!

2 Answers 2

1

Did you try [^{}]+ (with plus) instead of [^{}]*? Just because * matches also zero chars

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

2 Comments

Ah nice! answers my ancillary question at the end.. any ideas for my main problem? Thanks.
Well, because {} are special chars in regex - you specify quantity of matches with them. So a{17} means "a" 17 times. You just need to escape them, i.e. [^{}]+\{[^{}]+\}
0

Would you try using:

 NSString *needle = @"[^{}]*\{[^{}]*\}";

indeed, { and } have special meaning in regexs (but they are sort of "automatically" escaped when used within [])

5 Comments

Hmm.. no luck, don't think } requires escaping. It throughs up this : warning: unknown escape sequence '\}'. Thanks anyway!
what about: NSString *needle = @"[^{}]+[{][^{}]+[}]";
Yes!! Thanks! Now why on earth does it need that? [] around {}'s? Is it a way of escaping without \?
well, I don't know what are you using to match the regex (and it could be a fault in that library), but it is sure that {} are modifiers, so you cannot use them freely; on the other hand [] have the property of escaping their content, so it does the trick. The problem is why \{ and \} are rejected... that's why I think of a problem with the regex engine...
I'm using NSRegularExpression which is in the cocoa framework I think - I haven't used any external libraries.... Interesting I guess.

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.