It seems you need to match a hashtag at the end of the string, or the last hashtag in the string. So, there are several ways solve the issue.
Matching the last hashtag in the string
let str = "I made this wonderful pic last #chRistmas... #instagram #nofilter #snow #fun"
let regex = "#[[:alnum:]]++(?!.*#[[:alnum:]])"
if let range = str.range(of: regex, options: .regularExpression) {
let text: String = String(str[range])
print(text)
}
Details
#
- a hash symbol
[[:alnum:]]++
- 1 or more alphanumeric chars
(?!.*#[[:alnum:]])
- no #
+ 1+ alphanumeric chars after any 0+ chars other than line break chars immediately to the right of the current location.
Matching a hashtag at the end of the string
Same code but with the following regexps:
let regex = "#[[:alnum:]]+$"
or
let regex = "#[[:alnum:]]+\\z"
Note that \z
matches the very end of string, if there is a newline char between the hashtag and the end of string, there won't be any match (in case of $
, there will be a match).
Note on the regex
If a hashtag should only start with a letter, it is a better idea to use
#[[:alpha:]][[:alnum:]]*
where [[:alpha:]]
matches any letter and [[:alnum:]]*
matches 0+ letters or/and digits.
Note that in ICU regex patterns, you may write [[:alnum:]]
as [:alnum:]
.