Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Swift 3 (Xcode 8)
- ```swift
- func matches(for regex: String, in text: String) -> [String] {
- do {
- let regex = try NSRegularExpression(pattern: regex)
- let nsString = text as NSString
- let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
- return results.map { nsString.substring(with: $0.range)}
- } catch let error {
- print("invalid regex: \(error.localizedDescription)")
- return []
- }
- }
- ```
- Example:
- ```swift
- let string = "🇩🇪€4€9"
- let matched = matches(for: "[0-9]", in: string)
- print(matched)
- // ["4", "9"]
- ```
- ---
- As of Swift 4 (Xcode 9), the Swift standard library provides functions to convert between Range<String.Index> and NSRange.
- ```
- func matches(for regex: String, in text: String) -> [String] {
- do {
- let regex = try NSRegularExpression(pattern: regex)
- let results = regex.matches(in: text,
- range: NSRange(text.startIndex..., in: text))
- return results.map {
- String(text[Range($0.range, in: text)!])
- }
- } catch let error {
- print("invalid regex: \(error.localizedDescription)")
- return []
- }
- }
- ```
- Example:
- ```
- let string = "🇩🇪€4€9"
- let matched = matches(for: "[0-9]", in: string)
- print(matched)
- // ["4", "9"]
- ```
- Note: The forced unwrap Range($0.range, in: text)! is safe because the NSRange refers to a substring of the given string text. However, if you want to avoid it then use
- ```
- return results.flatMap {
- Range($0.range, in: text).map { String(text[$0]) }
- }
- ```
- extension String
- {
- func hashtags() -> [String]
- {
- if let regex = try? NSRegularExpression(pattern: "#[a-z0-9]+", options: .caseInsensitive)
- {
- let string = self as NSString
- return regex.matches(in: self, options: [], range: NSRange(location: 0, length: string.length)).map {
- string.substring(with: $0.range).replacingOccurrences(of: "#", with: "").lowercased()
- }
- }
- return []
- }
- }
Add Comment
Please, Sign In to add comment