我有这个字符串(2.5+1)*5
我想制作一个包含每个元素的 NSMutableArray:
[(, 2.5, +, 1, ), *, 5]
这是我写的代码:
+ (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);
}
我得到这个输出:
(
"<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}"
)
在Java中我得到了答案:
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;
}
哪个有效,但我无法在 Objective-c 中翻译它