Tometoyou Tometoyou - 1 year ago 139
iOS Question

Use regex to match emojis as well as text in string

I am trying to find the range of specific substrings of a string. Each substring begins with a hashtag and can have any character it likes within it (including emojis). Duplicate hashtags should be detected at distinct ranges. A kind user from here suggested this code:

var str = "The range of #hashtag should be different to this #hashtag"
let regex = try NSRegularExpression(pattern: "(#[A-Za-z0-9]*)", options: [])
let matches = regex.matchesInString(str, options:[], range:NSMakeRange(0, str.characters.count))
for match in matches {
print("match = \(match.range)")

However, this code does not work for emojis. What would be the regex expression to include emojis? Is there a way to detect a
, followed by any character up until a space/line break?

Answer Source

Similarly as in Swift extract regex matches, you have to pass an NSRange to the match functions, and the returned ranges are NSRanges as well. This can be achieved by converting the given text to an NSString.

The #\S+ pattern matches a # followed by one or more non-whitespace characters.

let text = "The 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download