regex

Regex for a valid hashtag


I need regular expression for validating a hashtag. Each hashtag should starts with hashtag("#").

Valid inputs:

1. #hashtag_abc

2. #simpleHashtag

3. #hashtag123

Invalid inputs:

1. #hashtag#

2. #hashtag@hashtag

I have been trying with this regex /#[a-zA-z0-9]/ but it is accepting invalid inputs also.

Any suggestions for how to do it?


Solution

  • To answer the current question...

    There are 2 issues:

    Since you are validating the whole string, you also need anchors (^ and $)to ensure a full string match:

    /^#\w+$/
    

    See the regex demo.

    If you want to extract specific valid hashtags from longer texts...

    This is a bonus section as a lot of people seek to extract (not validate) hashtags, so here are a couple of solutions for you. Just mind that \w in JavaScript (and a lot of other regex libraries) equal to [a-zA-Z0-9_]:

    And last but not least, here is a Twitter hashtag regex from https://github.com/twitter/twitter-text/tree/master/js... Sorry, too long to paste in the SO post, here it is: https://gist.github.com/stribizhev/715ee1ee2dc1439ffd464d81d22f80d1.