Regex to find hashtags

Use /\B#[A-Za-z0-9_]+/g to find every match in a text. Every example below is tested against the pattern, and you can open it in the Regex Tester with the samples preloaded.

Updated

/\B#[A-Za-z0-9_]+/g
Open in Regex Tester

Sample text

Loving #regex and #JavaScript_tips! Not a tag: issue#42 or a lone # sign. #2026goals

3 matches

#regex #JavaScript_tips #2026goals

How the pattern works

PartMeaning
\BNot a word boundary — the # must not follow a letter or digit, so issue#42 is skipped
#The hash sign
[A-Za-z0-9_]+The tag: letters, digits and underscores

Code examples

JavaScript

const matches = text.match(/\B#[A-Za-z0-9_]+/g) ?? [];

Python

import re

matches = re.findall(r'\B#[A-Za-z0-9_]+', text)

PHP

preg_match_all('/\B#[A-Za-z0-9_]+/', $text, $m);
$matches = $m[0];

Notes and limitations

To support hashtags in any language, use \B#[\p{L}\p{N}_]+ with the u flag in JavaScript (Python needs the third-party regex module for \p{…}).

Regex TesterType a pattern and watch matches highlight live in your test text.
Open the tool

Frequently asked questions

What is the regex to find hashtags?
/\B#[A-Za-z0-9_]+/g — it finds every match in a text. See the table above for what each part does.
Does it work in Python and PHP?
Yes — the code examples above use the same pattern with re in Python and preg functions in PHP.
How do I test this regex?
Click “Open in Regex Tester” — the pattern, flags and sample text load automatically, and matches highlight as you edit.