find hashtags in a string using regex in swift

In Swift, you can use the NSRegularExpression class to find hashtags in a string using regex. Here's an example:

main.swift
let string = "I love #coding and #programming in #Swift"
let regex = try? NSRegularExpression(pattern: "(?:^|\\s)(\\#\w+)", options: .caseInsensitive)
let matches = regex?.matches(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count))

if let matches = matches {
    let hashtags = matches.map {
        String(string[Range($0.range, in: string)!])
    }
    print(hashtags)
}
404 chars
11 lines

This code creates a regular expression pattern that matches hashtags (words that begin with a # symbol) and then finds all occurrences of this pattern in the input string. It then extracts the actual hashtags from the matches and prints them to the console.

Note that this regex pattern matches hashtags only if they are preceded by white space or are at the beginning of the string.

gistlibby LogSnag