我的应用程序中有一个如下所示的字符串:
b=c+32
我使用下面的代码片段解析字符串,将其拆分为b,=,c,+,32。这很好。但是我需要知道哪个变量是" ="的左侧。运营商。该变量始终位于表达式的第一位。在NSRegularExpressions中有没有办法给我结果索引,所以我可以比较它们以查看" ="的左侧。如果有一个更好的匹配,这将给我第一个元素,我也会满足于此。
这是拆分它们的代码。
NSString * textpattern = @"[A-Za-z]+";
NSString * numberpattern = @"[0-9]+";
NSString * opPattern = @"[-+/*]";
NSString * copPattern = @"=";
NSRegularExpression * reg = [NSRegularExpression regularExpressionWithPattern: @"(\\d+\\.\\d+)|(\\d+)|([a-z])|([+-/*=///^])|([/(/)])" options:0 error:nil];
NSArray *matches = [ reg matchesInString: exp
options: 0
range:NSMakeRange(0, [exp length])];
for (NSTextCheckingResult *match in matches) {
NSString* text = [exp substringWithRange:[match range]];
NSMutableDictionary *term = [NSMutableDictionary new];
if ([text doesMatchRegStringExp:textpattern])
{
NSLog(@"variable");
[term setObject:@"variable" forKey:@"name"];
}
else if ([text doesMatchRegStringExp:numberpattern])
{
NSLog(@"number");
[term setObject:@"number" forKey:@"name"];
}
else if ([text doesMatchRegStringExp:opPattern])
{
NSLog(@"op");
[term setObject:@"op" forKey:@"name"];
}
else if ([text doesMatchRegStringExp:copPattern])
{
NSLog(@"cop");
[term setObject:@"cop" forKey:@"name"];
}
else
{
[term setObject:@"other" forKey:@"name"];
}
}
// NSString+RegExpExtensions.h
#import <Foundation/Foundation.h>
@interface NSString (RegExpExtensions)
- (BOOL)doesMatchRegStringExp:(NSString *)string;
@end
#import "NSString+RegExpExtensions.h"
@implementation NSString (RegExpExtensions)
- (BOOL)doesMatchRegStringExp:(NSString *)string {
NSPredicate *regExpPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", string];
return [regExpPredicate evaluateWithObject:self];
}
@end
谢谢。