KevinVuD
KevinVuD

Reputation: 611

How to get hashtag from string that contains # at the beginning and end without space at the end?

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

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

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.

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:].

Upvotes: 2

abskmj
abskmj

Reputation: 758

You can use: (^#[a-z0-9]+|#[a-z0-9]+$)

Test it online

Upvotes: 1

trungduc
trungduc

Reputation: 12154

Using #[a-zA-Z0-9]*$ instead of your current regex

Upvotes: 2

Related Questions