我有一个字符串:
let s : String = "The dog ate the cat."
使用以下模式:
let p : NSRegularExpression = try! NSRegularExpression(pattern: "\\w( )?dog( )?\\w"), options: .CaseInsensitive)
我的问题是:如何在模式出现之前和之后得到单词?
这是我目前的实施:
let t : [NSTextCheckingResults] = p.matchesInString(s, options: [], NSMakeRange(0, NSString(string: s).length))
print(String(t[0].URL!))
然而,这不会返回所需的结果。
我的正则表达式出了什么问题?
答案 0 :(得分:1)
试试这个:
extension String {
subscript (range: NSRange) -> String {
let startIndex = self.startIndex.advancedBy(range.location)
let endIndex = startIndex.advancedBy(range.length)
return self[startIndex..<endIndex]
}
}
let s = "The dog ate the cat."
let pattern = try! NSRegularExpression(pattern: "(\\w+)?\\s?dog\\s?(\\w+)?", options: [.CaseInsensitive])
let matches = pattern.matchesInString(s, options: [], range: NSMakeRange(0, s.characters.count))
for m in matches {
print(s[m.rangeAtIndex(0)])
let range1 = m.rangeAtIndex(1)
if range1.location != NSNotFound {
print("capture group 1:", s[range1])
}
let range2 = m.rangeAtIndex(2)
if range2.location != NSNotFound {
print("capture group 2:", s[range2])
}
}
String
的扩展名是可选的,但它可以更轻松地使用NSRange
。使用(\\w+)?
使2个捕获组成为可选项,因此它也匹配以下字符串:
// The dog ate the cat
The dog ate
capture group 1: the
capture group 2: ate
// dog ate my home work
dog ate
capture group 2: ate
// I love my dog
my dog
capture group 1: my
// dog
dog