I have this string (2.5+1)*5
I want to make a NSMutableArray containing each of the elements:
[(, 2.5, +, 1, ), *, 5]
This is the code I wrote:
+ (NSMutableArray*) convertToList: (NSString *) exp {
NSRegularExpression * reg = [NSRegularExpression regularExpressionWithPattern: @"(\\d+\\.\\d+)|(\\d+)|([+-/*///^])|([/(/)])" options:0 error:nil];
NSArray *matches = [ reg matchesInString: exp
options: 0
range:NSMakeRange(0, [exp length])];
return [matches mutableCopy];
}
int main (int argc, char *argv[]) {
NSString * exp = @"(2+5)";
NSMutableArray * array = [ExpressionTexting convertToList:exp];
NSLog(@"%@", array);
}
I get this output:
(
"<NSExtendedRegularExpressionCheckingResult: 0x10010d2e0>{0, 1}{<NSRegularExpression: 0x10010abb0> (\\d+\\.\\d+)|(\\d+)|([+-/*///^])|([/(/)]) 0x0}",
"<NSExtendedRegularExpressionCheckingResult: 0x10010d3f0>{1, 1}{<NSRegularExpression: 0x10010abb0> (\\d+\\.\\d+)|(\\d+)|([+-/*///^])|([/(/)]) 0x0}",
"<NSExtendedRegularExpressionCheckingResult: 0x10010d470>{2, 1}{<NSRegularExpression: 0x10010abb0> (\\d+\\.\\d+)|(\\d+)|([+-/*///^])|([/(/)]) 0x0}",
"<NSExtendedRegularExpressionCheckingResult: 0x10010d4f0>{3, 1}{<NSRegularExpression: 0x10010abb0> (\\d+\\.\\d+)|(\\d+)|([+-/*///^])|([/(/)]) 0x0}",
"<NSExtendedRegularExpressionCheckingResult: 0x10010d570>{4, 1}{<NSRegularExpression: 0x10010abb0> (\\d+\\.\\d+)|(\\d+)|([+-/*///^])|([/(/)]) 0x0}"
)
In Java I got the answer:
public static ArrayList<String> convertToList(String exp){
String regex = "(\\d+\\.\\d+)|(\\d+)|([+-/*///^])|([/(/)])";
Matcher m3 = Pattern.compile(regex).matcher(exp);
ArrayList<String> list = new ArrayList<String>(exp.length());
while (m3.find()) {
list.add(m3.group());
}
return list;
}
Which works, but I can’t translate it in Objective-c
I found the solution, the error was due to the fact that I didn’t really know how to handle the result, the NSArray returned is made of NSTextCheckingResult, which I have to use to extract the numbers and the operators.