Reputation: 611
This is my string
"I made this wonderful pic last #chRistmas... #instagram #nofilter #snow #fun"
and I would like to get hashtag that contains # at the beginning and end without space. My expected result is:
$fun
This is what I have so far for regex search:
#[a-z0-9]+
but it give me all the hashtags not the one that I want. Thank you for your help!
Upvotes: 2
Views: 2041
Reputation: 627341
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.
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.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:]
.
Upvotes: 2