使用带有“单词边界模式”的“正则表达式”搜索\b
:
NSString *text = @"Here is my string. His isn't a mississippi isthmus. It is...";
NSString *pattern = @"\\bis\\b";
NSRange range = [text rangeOfString:pattern options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
if (range.location != NSNotFound) { ... }
这也适用于"Is it?"
or之类的情况"It is!"
,其中单词没有被空格包围。
在Swift 2中,这将是
let text = "Here is my string. His isn't a mississippi isthmus. It is..."
let pattern = "\\bis\\b"
if let range = text.rangeOfString(pattern, options: [.RegularExpressionSearch, .CaseInsensitiveSearch]) {
print ("found:", text.substringWithRange(range))
}
斯威夫特 3:
let text = "Here is my string. His isn't a mississippi isthmus. It is..."
let pattern = "\\bis\\b"
if let range = text.range(of: pattern, options: [.regularExpression, .caseInsensitive]) {
print ("found:", text.substring(with: range))
}
斯威夫特 4:
let text = "Here is my string. His isn't a mississippi isthmus. It is..."
let pattern = "\\bis\\b"
if let range = text.range(of: pattern, options: [.regularExpression, .caseInsensitive]) {
print ("found:", text[range])
}
Swift 5(使用新的原始字符串文字):
let text = "Here is my string. His isn't a mississippi isthmus. It is..."
let pattern = #"\bis\b"#
if let range = text.range(of: pattern, options: [.regularExpression, .caseInsensitive]) {
print ("found:", text[range])
}