1

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?

Community
  • 1
  • 1
Natan R.
  • 5,141
  • 1
  • 31
  • 48

3 Answers3

3

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!

Ron
  • 1,047
  • 13
  • 18
  • indeed, this is a solution! +1 that it helps me, but i'm pretty curious how I could do it with Regex – Natan R. Nov 15 '12 at 13:05
1

Use

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

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

Community
  • 1
  • 1
Ωmega
  • 42,614
  • 34
  • 134
  • 203
0

To do this with regex:

(?<=START\s)(.+?)(?=\sEND)
garyh
  • 2,782
  • 1
  • 26
  • 28