user3315336 user3315336 - 4 years ago 80
Javascript Question

Regex for set of Hashtags

I need a regular expression for validating one or more hashtags. Each hashtag should start with hash ("#") and ends with comma or space.

These are the valid inputs:

#hashtagTest


#hashtagTest1, #hashtagTest2


#hashtagTest1,#hashtagTest2


I've been trying to do this in javascript but with no success so far.

These are invalid inputs:

#hashtagTest hashtagTest


#hashtagTest#hashtagTest

Answer Source

This one will work

/(#[a-zA-Z0-9]+,? *)*#[a-zA-Z0-9]+/

See the explanation and test it here https://regex101.com/r/0NJkgq/2

You might want to add begin and end of line markers to make sure the whole string is a sequence of tags

/^(#[a-zA-Z0-9]+,? *)*#[a-zA-Z0-9]+$/

If you want to find all the occurrences of sequences of tags in a string you can use

/(#[a-zA-Z0-9]+,? *)*#[a-zA-Z0-9]+/g

The g modifiers allows to find all the occurrences of the regexp in a string

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download