Reputation: 11
i have a list of string i want search string like A mean it is only appearance in middle not first or last.My code here: When i run all 3 case is true, but only case "う上あ" is true
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSArray *array = @[@"上あう", @"う上あ", @"あう上"];
NSString *stringNeedToFind = @"*上*";
for (NSString *string in array) {
if ([[self regularExpressionFromValue: stringNeedToFind] numberOfMatchesInString:string options: 0 range: NSMakeRange(0, string.length)]) {
NSLog(@"String containt.");
}
}
}
- (NSRegularExpression *) regularExpressionFromValue: (NSString *) value
{
NSString *pattern = [NSRegularExpression escapedPatternForString: value];
pattern = [pattern stringByReplacingOccurrencesOfString: @"\\*" withString: @".*"];
pattern = [pattern stringByReplacingOccurrencesOfString: @"\\?" withString: @"."];
pattern = [pattern stringByReplacingOccurrencesOfString: @".*.*.*" withString: @"\\*"];
pattern = [pattern stringByReplacingOccurrencesOfString: @"..." withString: @"\\?\\?\\?"];
pattern = [NSString stringWithFormat: @"^%@$", pattern];
return [NSRegularExpression regularExpressionWithPattern: pattern options: 0 error: NULL];
}
Upvotes: 1
Views: 230
Reputation: 1434
As far as I know, the asterisk (*) is used as an operator to check if a character (set) is present 0 or more times. I think you should use the plus character (+), e.g. like this: ^.+上.+$, meaning there should be 1 or more characters at the start and at the end.
Upvotes: 1