1

Given the following pattern: "##-##-##", where "##" represents a 1 or 2 digit integer, what is the best way to separate the numbers?

Some background: I have an array of NSString objects. From this array I create a new mutable array, converting some of the strings into NSNumbers (this is working). Some of the strings have the pattern shown above (the pattern represents wins, losses and ties). I want to add to the mutable array, the string (as is) as well as the wins, losses, and ties as NSIntegers.

I don't know if it would be better to use an NSScanner or NSRegularExpression. I have not used either of these before and I'm not sure how to set them up and return the info that I need.

Thanks in advance,
Brad

2
  • Some people prefer NSScanner, and other prefer NSRegularExpression. For this task, both would work. Or simply use componentsSeparatedByString ... Commented Feb 1, 2014 at 18:39
  • @MartinR I hadn't thought of using componentsSeparatedByString. It'll be easy to cycle through the resulting array to add each object to the mutable array. How to I check for the pattern though? Commented Feb 1, 2014 at 18:52

2 Answers 2

1

If you want to use NSRegularExpression then try like this:-

 NSRegularExpression *regex = 
 [NSRegularExpression 
 regularExpressionWithPattern:@"-"
options:NSRegularExpressionCaseInsensitive
error:nil];

NSArray *matches = [regex 
 matchesInString:string  options:0
 range:NSMakeRange(0, [string length])];
Sign up to request clarification or add additional context in comments.

Comments

1

You can use [NSString componentsSeparatedByString:@"-"]. For your case is simple. The rest I believe it is overkill.

NSString *completeString= @"20-33-89";
NSArray *numbers = [completeString componentsSeparatedByString:@"-"];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.