Jos*_*hua 40 cocoa objective-c nsstring
我如何通过NSString使用正则表达式来搜索/枚举?
正则表达式如:/(NS|UI)+(\w+)/g.
Pab*_*ruz 57
你需要使用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
}];
Run Code Online (Sandbox Code Playgroud)
ved*_*ano 35
如果您只想匹配字符串中的某些模式,可以使用以下方法测试正则表达式NSString:
NSString *string = @"Telecommunication";
if ([string rangeOfString:@"comm" options:NSRegularExpressionSearch].location != NSNotFound)
NSLog(@"Got it");
else
NSLog(@"No luck");
Run Code Online (Sandbox Code Playgroud)
请注意,通常你会想...
if ([string rangeOfString:@"cOMm"
options:NSRegularExpressionSearch|NSCaseInsensitiveSearch].location
!= NSNotFound)
NSLog(@"yes match");
Run Code Online (Sandbox Code Playgroud)
在Swift中你可以编写这样的代码......
let string = "Telecommunication"
if string.rangeOfString("cOMm", options: (NSStringCompareOptions.RegularExpressionSearch | NSStringCompareOptions.CaseInsensitiveSearch)) != nil {
print("Got it")
} else {
print("No luck")
}
Run Code Online (Sandbox Code Playgroud)
let string = "Telecommunication"
if string.range(of: "cOMm", options: [.regularExpression, caseInsensitive]) != nil {
print("Got it")
} else {
print("No luck")
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果搜索失败,Swift 2 rangeOfString(_:,options:)和Swift 4的range(of:options:)返回值Range<String.Index>?将返回nil
| 归档时间: |
|
| 查看次数: |
42046 次 |
| 最近记录: |