gamersoul
gamersoul

Reputation: 101

multiple matches for NSRegularExpression

I have the following regex pattern to match:

NSString *pattern=[NSString stringWithFormat:@"%@(.*)%@", key, key2];

So let say if key=\\\\[\\\\\[ and key2=\\\\]\\\\] then I am getting the string containing the keys along with the contained text. But the problem is that if there are multiple matches then it only takes ist appearance of key and last appearance of key2 and gives me the text contained between those along with the keys. Eg.: This is [[some]] [[text]]. This gives me:[[some]] [[text]] as one match whereas I want [[some]] and [[text]] as separate matches. How should I modify it to give all the matches separately?

Upvotes: 0

Views: 333

Answers (1)

user529758
user529758

Reputation:

Same thing that bothers novice parser makers who wanna parse a string between quotes, and think that

\\".*\\"

is sufficient, but then are surprised when this matches all the text between

"a string" and also "another string"

The reason behind this is that the * operator is greedy. You have to use character set negation to achieve the expected result:

\\[\\[[^\\[\\]]*\\]\\]

Hope this helps.

Upvotes: 1

Related Questions