I want to extract substrings from a string that match a regex pattern.
So I\'m looking for something like this:
func matchesForRegexInText(regex: St
I found that the accepted answer's solution unfortunately does not compile on Swift 3 for Linux. Here's a modified version, then, that does:
import Foundation
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try RegularExpression(pattern: regex, options: [])
let nsString = NSString(string: text)
let results = regex.matches(in: text, options: [], range: NSRange(location: 0, length: nsString.length))
return results.map { nsString.substring(with: $0.range) }
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
The main differences are:
Swift on Linux seems to require dropping the NS
prefix on Foundation objects for which there is no Swift-native equivalent. (See Swift evolution proposal #86.)
Swift on Linux also requires specifying the options
arguments for both the RegularExpression
initialization and the matches
method.
For some reason, coercing a String
into an NSString
doesn't work in Swift on Linux but initializing a new NSString
with a String
as the source does work.
This version also works with Swift 3 on macOS / Xcode with the sole exception that you must use the name NSRegularExpression
instead of RegularExpression
.