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:


#hashtagTest1, #hashtagTest2


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

These are invalid inputs:

#hashtagTest hashtagTest


Answer Source

This one will work

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

See the explanation and test it here

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