Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // MARK: - Regular Expression
- private extension String
- {
- func regexp(_ pattern: String) -> NSRegularExpression {
- do {
- let regexp: NSRegularExpression = try NSRegularExpression(pattern: pattern, options: [NSRegularExpression.Options.caseInsensitive])
- return regexp
- } catch {
- fatalError("regular expression pattern is invalid.")
- }
- }
- }
- // MARK: - Regular Expression
- public extension String
- {
- public func regexMatched(withPattern pattern: String) -> Bool {
- let regexp: NSRegularExpression = self.regexp(pattern)
- return 0 < regexp.numberOfMatches(in: self, options: [], range: NSRange(location: 0, length: (self as NSString).length))
- }
- public func regexStrings(withPattern pattern: String) -> [String] {
- let regexp: NSRegularExpression = self.regexp(pattern)
- let matches: [NSTextCheckingResult] = regexp.matches(in: self, options: [], range: NSRange(location: 0, length: (self as NSString).length))
- let result: [String] = matches.map { (match: NSTextCheckingResult) in
- (self as NSString).substring(with: match.range)
- }
- return result
- }
- public func regexReplace(withPattern pattern: String, replace: String) -> String
- {
- let regexp: NSRegularExpression = self.regexp(pattern)
- let matches: [NSTextCheckingResult] = regexp.matches(in: self, options: [], range: NSRange(location: 0, length: (self as NSString).length))
- var result: String = self
- matches.reversed().forEach { (match: NSTextCheckingResult) in
- result = (result as NSString).replacingCharacters(in: match.range, with: replace)
- }
- return result
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement