find mentions in a string using regex in swift

To find mentions in a string using regex in Swift, you can use the NSRegularExpression class that is available in the Foundation framework.

Here's an example code snippet that shows how you can extract mentions from a string using regex:

main.swift
let string = "@john and @jane are going to the party"
let regex = try! NSRegularExpression(pattern: "@(\\w+)", options: [])

let matches = regex.matches(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count))

let mentions = matches.map {
    String(string[Range($0.range, in: string)!])
}
316 chars
9 lines

In the above code, we first define the string that we want to extract mentions from. We then create a pattern that matches the "@" symbol followed by one or more word characters. The pattern is enclosed in a capturing group so that we can extract the matched text later.

We then create an instance of the NSRegularExpression class with the pattern and specify that we don't need any options.

Next, we use the matches(in:options:range:) method of the NSRegularExpression class to find all matches of the pattern in the string. The returned value is an array of NSTextCheckingResult objects.

Finally, we extract the matched text from each NSTextCheckingResult object using the Range(_:, in:) method of the string and store them in an array. The resulting mentions array contains all the mentions in the original string.

Note that the above code assumes that the string only contains mentions that start with "@" followed by one or more word characters. If you need to handle other cases, you may need to modify the regex pattern accordingly.

gistlibby LogSnag