(请简短说明以帮助他人)
检查字符串是否与正则表达式匹配:
-- SomeText: Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Integer rutrum neque euismod ante pulvinar gravida. In viverra
sollicitudin libero nec ullamcorper. Nam porta luctus leo, vel
porttitor enim rutrum id. Fusce lacus odio, facilisis eget ligula et,
consequat faucibus turpis. Vestibulum sed placerat leo, eu rhoncus leo.
检查所选字符串是否匹配:
text.range(of: regex, options: .regularExpression) == nil
答案 0 :(得分:2)
第一个很简单,我们实际上不需要NSRegularExpression
:
extension String {
func hasMatches(_ pattern: String) -> Bool {
return self.range(of: pattern, options: .regularExpression) != nil
}
}
let regex = "(.*) [:] (.*)"
let string = "Tom : how are you?"
print(string.hasMatches(regex))
我想说的是,我们甚至不需要实用程序功能。
第二个难以理解,主要是因为NSRegularExpression
API并未真正转换为Swift,它甚至使用了旧的NSString
:
extension String {
func getMatches(_ pattern: String) throws -> [[String]] {
let nsString = self as NSString
let expression = try NSRegularExpression(pattern: pattern)
let matches = expression
.matches(in: self, options: [], range: NSRange(location: 0, length: nsString.length))
return matches.map { match in
let numGroups = match.numberOfRanges
// we are skipping group 0 which contains the pattern itself
return (1 ..< numGroups)
.map { groupIndex in
return nsString.substring(with: match.range(at: groupIndex))
}
}
}
}
print(try! string.getMatches(regex)) // [["Tom", "how are you?"]]
请注意,我要返回一个数组数组,因为表达式可以匹配多次。
例如:
let regex = "(\\d+):(\\d+)"
let string = "01:23, 02:34"
print(try! string.getMatches(regex)) // [["01", "23"], ["02", "34"]]