将 JavaScript 正则表达式转换为 Swift 正则表达式 [英] Convert a JavaScript Regex to a Swift Regex
问题描述
我正在学习 Swift,并且正在尝试将一小段 JavaScript 代码转换为 Swift.JavaScript 代码使用 Regex 拆分字符串,如下所示:
I'm learning Swift, and I'm trying to convert a small bit of JavaScript code to Swift. The JavaScript code uses a Regex to split up a string, as shown below:
var text = "blah.clah##something_else";
var parts = text.match(/(^.*?)\#\#(.+$)/);
执行后,parts
数组将包含以下内容:
after execution, the parts
array will then contain the following:
["blah.clah##something_else", "blah.clah", "something_else"]
我想在 Swift 中复制相同的行为.下面是我编写的使用正则表达式将字符串拆分为字符串数组的 Swift 代码:
I would like to replicate the same behavior in Swift. Below is the Swift code I've written to do split up a String into a String array using a Regex:
func matchesForRegexInText(regex: String!, text: String!) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex, options: NSRegularExpressionOptions.CaseInsensitive)
let nsString = text as NSString
let results = regex.matchesInString(text,
options: NSMatchingOptions.ReportCompletion , range: NSMakeRange(0, nsString.length))
as [NSTextCheckingResult]
return results.map({
nsString.substringWithRange($0.range)
})
} catch {
print("exception")
return [""]
}
}
当我使用以下命令调用上述函数时:
When I call the above function with the following:
matchesForRegexInText("(^.*?)\\#\\#(.+$)", text: "blah.clah##something_else")
我得到以下信息:
["blah.clah##something_else"]
我尝试了许多不同的正则表达式,但都没有成功.Regex (^.*?)\#\#(.+$) 是否正确,或者matchesForRegexInText() 函数有问题?我很感激任何见解.
I've tried a number of different Regex's without success. Is the Regex (^.*?)\#\#(.+$) correct, or is there a problem with the matchesForRegexInText() function? I appreciate any insight.
我使用的是 Swift 2 和 Xcode 7.0 测试版 (7A120f)
I'm using Swift 2, and Xcode Version 7.0 beta (7A120f)
推荐答案
正如评论中已经提到的,您的模式匹配整个字符串,所以 regex.matchesInString()
返回一个NSTextCheckingResult
其 range
描述了整个字符串.您要查找的是与 捕获组 匹配的子字符串在你的模式中.这些可以作为 rangeAtIndex(i)
使用,i >= 1
:
As already mentioned in a comment, your pattern matches the entire
string, so regex.matchesInString()
returns a single
NSTextCheckingResult
whose range
describes the entire string.
What you are looking for are the substrings matching the capture groups
in your pattern. These are available as rangeAtIndex(i)
with i >= 1
:
func matchesForRegexInText(regex: String!, text: String!) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex, options: [])
let nsString = text as NSString
guard let result = regex.firstMatchInString(text, options: [], range: NSMakeRange(0, nsString.length)) else {
return [] // pattern does not match the string
}
return (1 ..< result.numberOfRanges).map {
nsString.substringWithRange(result.rangeAtIndex($0))
}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
示例:
let matches = matchesForRegexInText("(^.*?)##(.+$)", text: "blah.clah##something_else")
print(matches)
// [blah.clah, something_else]
这篇关于将 JavaScript 正则表达式转换为 Swift 正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!