session-ios/SignalServiceKit/src/Util/NSRegularExpression+SSK.swift

56 lines
2.0 KiB
Swift
Raw Normal View History

2019-01-10 19:21:33 +01:00
//
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
@objc
public extension NSRegularExpression {
@objc
public func hasMatch(input: String) -> Bool {
return self.firstMatch(in: input, options: [], range: NSRange(location: 0, length: input.utf16.count)) != nil
}
2019-01-17 20:56:46 +01:00
@objc
public class func parseFirstMatch(pattern: String,
text: String,
options: NSRegularExpression.Options = []) -> String? {
2019-01-17 20:56:46 +01:00
do {
let regex = try NSRegularExpression(pattern: pattern, options: options)
2019-01-17 20:56:46 +01:00
guard let match = regex.firstMatch(in: text,
options: [],
range: NSRange(location: 0, length: text.utf16.count)) else {
2019-01-17 20:56:46 +01:00
return nil
}
let matchRange = match.range(at: 1)
guard let textRange = Range(matchRange, in: text) else {
owsFailDebug("Invalid match.")
return nil
}
let substring = String(text[textRange])
return substring
} catch {
Logger.error("Error: \(error)")
return nil
}
}
2019-03-15 02:24:15 +01:00
@objc
public func parseFirstMatch(inText text: String,
options: NSRegularExpression.Options = []) -> String? {
guard let match = self.firstMatch(in: text,
options: [],
range: NSRange(location: 0, length: text.utf16.count)) else {
return nil
}
let matchRange = match.range(at: 1)
guard let textRange = Range(matchRange, in: text) else {
owsFailDebug("Invalid match.")
return nil
}
let substring = String(text[textRange])
return substring
}
2019-01-10 19:21:33 +01:00
}