-1

I try to find hashtags in

some words
#one #two
#three#four#five

by such an expression

(#.*?)(\s|#|$)

But can't find #four

enter image description here

holden321
  • 1,166
  • 2
  • 17
  • 32

1 Answers1

0

You can find all hashtags with this simple regex where there is absolutely no overlapping problem as you are facing in your current regex,

#\w+

Demo

Also, if you think your hashtag word can contain some more characters like - or or . You can modify your character set like this [\w.-]

Demo for enhanced character set

Here is a sample php code,

$str = "#one #two \n#three#four#five";
preg_match_all('/#\w+/s', $str, $matches);
for ($i=0;$i<count($matches[0]);$i++) {
    echo $matches[0][$i] . "\n";
}

This gives following output listing all hashtags found,

#one
#two
#three
#four
#five
Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36