Erlend
Erlend

Reputation: 1969

Regex to match a word with special characters that starts with hash and ends with space

Given the text:

This is a #tag and this is another #[email protected] and more text.

I would like to match the words starting with a hash and ends with a whitespace character ( i don't want to specify a specific pattern for #[email protected] ).

I can't use lookarounds and would prefer not to use \b.

I have tried #.*\b, #.*\s, which will match more than i asked for. I guess the * will also match whitespace so the last check is ignored.

I use https://regexr.com/ for testing.

Upvotes: 3

Views: 7149

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

You may use

#\S+

See the regex demo.

Details

  • # - a # symbol
  • \S+ - 1 or more characters other than whitespace (it can also be written as [^\s]*, but \S is just shorter).

As a possible enhancement, you can still consider using word and non-word boundaries. E.g., when you want to avoid matching abc#tagliketext or when you need to avoid matching punctuation at the end of the hashtag, you may consider using

\B#\S+\b

See another regex demo. The \B non-word boundary will fail the match if there is a word char before #, and \b will stop matching before the rightmost non-word char.

Upvotes: 7

Anmol Singh Jaggi
Anmol Singh Jaggi

Reputation: 8576

You can match every character except space in the middle.

Try this:

#[^\s]+\s

Demo

Upvotes: 3

Related Questions