Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a pound (#) symbol in a regex in php (for hashtags)

Tags:

regex

php

Very simple, I need to match the # symbol using a regex. I'm working on a hashtag detector.

I've tried searching in google and in stack overflow. One related post is here, but since he wanted to remove the # symbol from the string he didn't use regex.

I've tried the regexes /\b\#\w\w+/, and /\b#\w\w+/ and they don't work and if I remove the #, it detects the word.

like image 315
J-Rou Avatar asked Feb 23 '12 21:02

J-Rou


People also ask

What does hashtag mean in regex?

# does not have any special meaning in a regex, unless you use it as the delimiter. So just put it straight in and it should work. Note that \b detects a word boundary, and in #abc , the word boundary is after the # and before the abc . Therefore, you need to use the \b is superfluous and you just need #\w\w+ .


3 Answers

With the comment on the earlier answer, you want to avoid matching x#x. In that case, your don't need \b but \B:

\B#(\w\w+)

(if you really need two-or-more word characters after the #).

The \B means NON-word-boundary, and since # is not a word character, this matches exactly if the previous character is not a word character.

like image 53
Lasse Nielsen Avatar answered Oct 05 '22 02:10

Lasse Nielsen


# does not have any special meaning in a regex, unless you use it as the delimiter. So just put it straight in and it should work.

Note that \b detects a word boundary, and in #abc, the word boundary is after the # and before the abc. Therefore, you need to use the \b is superfluous and you just need #\w\w+.

like image 25
Niet the Dark Absol Avatar answered Oct 05 '22 00:10

Niet the Dark Absol


You don't need to escape it (it's probably the \b that's throwing it off):

if (preg_match('/^\w+#(\w+)/', 'abc#def', $matches)) {
    print_r($matches);
}

/* output of $matches:
Array
(
    [0] => abc#def
    [1] => def
)
*/
like image 38
webbiedave Avatar answered Oct 05 '22 02:10

webbiedave