-1

I have the following NSString:

@"Show study NCT01287026: Real-time MRI Right Heart Catheterization Using Passive Catheters"

From this, I need to create 2 new strings. One would hold the 11 characters of the NTC code:

@"NCT01287026" 

and the other the title of the study:

@"Real-time MRI Right Heart Catheterization Using Passive Catheters" 

I have several similar strings. They all start with "Show study NTC********". What is the best way to go about this?

I can find the occurrence of "NTC", but I am not sure how to create the new string with the 8 other characters which come after it. I also need the rest of the string (study title) which varies in length.

3 Answers3

1
NSArray *words = [input componentsSeparatedByString:@": "];
NSString *nct = [words[0] stringByReplacingOccurrencesOfString:@"Show study " withString:@""];
NSString *title = words[1];

Take a look at the NSString Class Reference or the String Programming Guide to learn about the many useful messages you can send to a string.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
1

You could use NSScanner for this:

NSString *string = @"Show study NCT01287026: Real-time MRI Right Heart Catheterization Using Passive Catheters";
NSString *nctString;
NSString *title;

NSScanner *scanner = [[NSScanner alloc] initWithString:string];
[scanner scanUpToString:@"NCT" intoString:nil];
[scanner scanUpToString:@":" intoString:&nctString];
[scanner scanString:@": " intoString:nil];
[scanner scanUpToCharactersFromSet:[NSCharacterSet illegalCharacterSet] intoString:&title];
dalton_c
  • 6,876
  • 1
  • 33
  • 42
0

You can select the first string using this regex: \d{8} (regexr)

This works for the second string: :.+ (regexr)

You can use these to get the string like so:

NSString *string = @"Show study NCT01287026: Real-time MRI Right Heart Catheterization Using Passive Catheters";
NSError *error;
NSRegularExpression *regex = [NSRegularExpression         
    regularExpressionWithPattern:@"\d{8}"
    options:NSRegularExpressionCaseInsensitive
    error:&error];
[regex enumerateMatchesInString:string options:0 range:NSMakeRange(0, [string length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
    //first match
}];

From: Search through NSString using Regular Expression

And repeat to using the second regex.

Community
  • 1
  • 1
67cherries
  • 6,931
  • 7
  • 35
  • 51