Regex for Matching a Hashtag

Matches a # symbol followed by one or more word characters.

Published October 12, 2026

This regex matches hashtags: a # followed by letters, digits or underscores.

How the pattern works

Breaking the pattern down: # = literal hash; \w+ = word characters.

Test your regex against both matching and non-matching inputs; use the Regex tool on this site to experiment live.

Pattern tests

/#\w+/
✓ 'I love #coding'
✓ '#php_8'
✗ 'no tag'
✗ '# alone'

Practical examples

The pattern

const re = /#\w+/

Test it

const re = /#\w+/
re.test('I love #coding')   // true
re.test('#php_8')   // true
re.test('no tag')   // false
re.test('# alone')   // false

In Python

import re
re.search(r'#\w+', text)

Common mistakes

  • Missing Unicode hashtags.
  • Matching URLs fragments (#section).
  • Forgetting the g flag for multiple tags.

Key takeaways

  • Anchors (^ and $) make the whole string match instead of a part of it.
  • Regex checks format only; verify data separately when it matters.
  • Test with valid and invalid samples.

FAQ

Capture the name only?

Use #(\w+).

Where can I test this pattern?

Use the Regex Tester on this site, or regex101.com.

More General articles