[英]Search through NSString using Regular Expression
我如何使用正則表達式搜索/枚舉NSString
?
正則表達式,例如: /(NS|UI)+(\\w+)/g
。
您需要使用NSRegularExpression
類。
示例受到文檔的啟發:
NSString *yourString = @"";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:@"(NS|UI)+(\\w+)"
options:NSRegularExpressionCaseInsensitive
error:&error];
[regex enumerateMatchesInString:yourString options:0 range:NSMakeRange(0, [yourString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
// your code to handle matches here
}];
如果您只想匹配字符串中的某些模式,可以使用NSString
測試正則表達式的簡單方法:
NSString *string = @"Telecommunication";
if ([string rangeOfString:@"comm" options:NSRegularExpressionSearch].location != NSNotFound)
NSLog(@"Got it");
else
NSLog(@"No luck");
請注意,通常你會想...
if ([string rangeOfString:@"cOMm"
options:NSRegularExpressionSearch|NSCaseInsensitiveSearch].location
!= NSNotFound)
NSLog(@"yes match");
在Swift中你可以編寫這樣的代碼......
let string = "Telecommunication"
if string.rangeOfString("cOMm", options: (NSStringCompareOptions.RegularExpressionSearch | NSStringCompareOptions.CaseInsensitiveSearch)) != nil {
print("Got it")
} else {
print("No luck")
}
let string = "Telecommunication"
if string.range(of: "cOMm", options: [.regularExpression, caseInsensitive]) != nil {
print("Got it")
} else {
print("No luck")
}
請注意Swift 2的rangeOfString(_:,options:)
和Swift 4的range(of:options:)
返回Range<String.Index>?
如果搜索失敗,則返回nil
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.