To find emojis in a string using regex in Swift, you can use the following regular expression pattern:
main.swift52 chars2 lines
This pattern matches any Unicode character that is not a control character (\p{C}
), a whitespace character (\p{Z}
), a punctuation character (\p{P}
), or a symbol character (\p{S}
). The 1,2
quantifier ensures that only valid emojis of length 1 or 2 are matched.
Then, you can use the NSRegularExpression
class to search for all matches of the pattern in your string:
main.swift315 chars10 lines
This will output:
main.swift9 chars4 lines
Note that some emojis may be represented by multiple Unicode characters, so you may want to normalize the string to ensure that all emojis are represented consistently. You can use the String
method precomposedStringWithCanonicalMapping
for this:
main.swift270 chars7 lines
This will output the same result as before.
gistlibby LogSnag