Yasser Farrag
Yasser Farrag

Reputation: 307

objective-c regular expressions match

If I have contiguous sentences and i want to match every of them, ex:

[symbol]bla bla bla bla[/symbol][symbol]text text text[/symbol]

i tried to math them like this :

"\[symbol].*[/symbol]]"

but it returned me the full string, how to match every part of them?

Upvotes: 1

Views: 83

Answers (3)

depsai
depsai

Reputation: 415

use this regex it will match want you want.

\[symbol\]((?:(?!\[\/?symbol\]).)*)\[\/symbol\]

See DEMO: http://regex101.com/r/aR7cG7/1

Upvotes: 0

Rob
Rob

Reputation: 438487

You want to use

  • *? - This will match as few as possible characters

  • I'm assuming that, in the results, you don't want the [symbol] and [/symbol], but rather just the text in-between. Thus, you can to use "capturing parentheses" to specify what to return.

  • You also want to "quote" the [ and / characters with backslash.

This yields:

\[symbol](.*?)\[\/symbol]

Obviously, when you want to represent \ in a string, though, you need to use \\. So that yields:

NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\[symbol](.*?)\\[\\/symbol]" options:NSRegularExpressionCaseInsensitive error:&error];
if (!regex) {
    NSLog(@"regex error: %@", error);
}

[regex enumerateMatchesInString:string options:0 range:NSMakeRange(0, [string length]) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
    NSString *foundString = [string substringWithRange:[result rangeAtIndex:1]]; // use result.range if you want to include the `[symbol]` and `[/symbol]`
    NSLog(@"%@", foundString);
}];

That produces:

2014-10-16 01:32:26.680 MyApp[66822:303] bla bla bla bla
2014-10-16 01:32:26.681 MyApp[66822:303] text text text

Upvotes: 0

nu11p01n73R
nu11p01n73R

Reputation: 26687

You need to be using a lazy .*? pattern

\[symbol\].*?\[\/symbol\]

will match

[symbol]bla bla bla bla[/symbol]

if you want to match all of them seperatly use a global(g) specifier

which will match seperatly

[symbol]bla bla bla bla[/symbol]
[symbol]text text text[/symbol]

Upvotes: 1

Related Questions