我需要在两个"%"之间提取字符串。字符,多次出现可以出现在查询字符串中。 现在使用以下正则表达式,有人可以帮助获得确切的Regax格式。
let query = "Hello %test% ho do you do %test1%"
let regex = try! NSRegularExpression(pattern:"%(.*?)%", options: [])
if let results = regex?.matchesInString(query, options: .Anchored, range: NSMakeRange(0,query.characters.count)){
for match in results{
}
}
答案 0 :(得分:15)
您的模式很好,但您的代码无法编译。试试这个:
let query = "Hello %test% how do you do %test1%"
let regex = try! NSRegularExpression(pattern:"%(.*?)%", options: [])
var results = [String]()
regex.enumerateMatches(in: query, options: [], range: NSMakeRange(0, query.utf16.count)) { result, flags, stop in
if let r = result?.range(at: 1), let range = Range(r, in: query) {
results.append(String(query[range]))
}
}
print(results) // ["test", "test1"]
NSString
使用UTF-16编码,因此使用UTF-16代码单元的数量调用NSMakeRange
。
let query = "Hello %test% how do you do %test1%"
let regex = try! NSRegularExpression(pattern:"%(.*?)%", options: [])
let tmp = query as NSString
var results = [String]()
regex.enumerateMatchesInString(query, options: [], range: NSMakeRange(0, tmp.length)) { result, flags, stop in
if let range = result?.rangeAtIndex(1) {
results.append(tmp.substringWithRange(range))
}
}
print(results) // ["test", "test1"]
从Swift的原生String
类型中获取子字符串有点麻烦。这就是我将query
投放到NSString
答案 1 :(得分:0)
我写了一个常规快递的方法。你的正则表达没问题。您可以测试正则表达式here。方法是:
func regexInText(regex: String!, text: String!) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex, options: [])
let nsString = text as NSString
let results = regex.matchesInString(text,
options: [], range: NSMakeRange(0, nsString.length))
return results.map { nsString.substringWithRange($0.range)}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
您可以随时调用它。