Natan R.
Natan R.

Reputation: 5191

Use regex to find and extract substrings from a string

Suppose I have the following string:

bla bla bla bla i don't know what to write START name 1 END more bla bla bla bla i don't know what to write START name 2 END more bla bla bla bla i don't know what to write START name 3 END

And I want to extract the following array:

name 1

name 2

name 3

What is the best way to do it with the iOS SDK?

Upvotes: 1

Views: 1434

Answers (3)

garyh
garyh

Reputation: 2852

To do this with regex:

(?<=START\s)(.+?)(?=\sEND)

Upvotes: 0

Ωmega
Ωmega

Reputation: 43703

Use

NSRegularExpression regularExpressionWithPattern:@"(?<=START ).*?(?= END)" 

See also Use regular expression to find/replace substring in NSString

Upvotes: 1

Ron
Ron

Reputation: 1047

Try this:

NSArray *names = [yourString componentsSeparatedByString:@"START"];

NSArray *namesArray = [NSArray array];

for (int i = 1; i < [names count]; i++) {
    NSString *thisLine = [names objectAtIndex:i];
    NSString *name = [thisLine substringToIndex:[thisLine rangeOfString:@"END"].location];

    [namesArray addObject:name];
    NSLog(@"Your name: %@", name);
}

Just noticed you wanted this with Regex... This is not that of course, but maybe it helps!

Upvotes: 3

Related Questions