-3

I need a regex to match a word that starts with #.

I wrote this question How to match a pound (#) symbol in a regex in php (for hashtags), but I forgot to explain that I need the # at the beginning of a word.

I need to match #word, #123, #12_sdas, but not 1#234 or #1234.

For example, in "#match1 notMatch not#Match #match2 notMatch #match3", only #match1, #match2 and #match3 should appear.

Edit: I just want one pound (#), followed by one or more [a-ZA-Z0-9_]. The match can't have any of [a-ZA-Z0-9_] before.

My problem was finding the pound at the beginning of the word.

Community
  • 1
  • 1
J-Rou
  • 2,216
  • 8
  • 32
  • 39
  • see the list of related posts on the right. –  Feb 23 '12 at 22:49
  • 2
    I think you need to give a clearer explanation what exactly should be matched. It's not clear in which cases numbers are allowed. (e.g. why match #123 but not #1234) – s1lence Feb 23 '12 at 23:56

2 Answers2

4
preg_match_all('/(?:^|\s)(#\w+)/', $string, $results);

EDIT: don't have a php cli to test this, but the regex works in python at the very least.

bluepnume
  • 16,460
  • 8
  • 38
  • 48
1

Try this:

preg_match_all('/(?:^|\s+)(#\w+)/', $your_input, $your_results);
// print results
print_r($your_results);

It will match all words beginning with a # symbol. Words can be sepearted by all valid whitespace characters (so one of \t\r\n\v\f)

Example

//input
#match1 notMatch not#Match #match2 notMatch #match3
//output
Array
(
    [0] => Array
        (
            [0] => #match1
            [1] =>  #match2
            [2] =>  #match3
        )

    [1] => Array
        (
            [0] => #match1
            [1] => #match2
            [2] => #match3
        )

)
s1lence
  • 2,188
  • 2
  • 16
  • 34