-3

我需要一个正则表达式来匹配以 # 开头的单词。

我写了这个问题How to match a pound (#) symbol in a regex in php (for hashtags),但我忘了解释我需要在单词的开头使用 # 。

我需要匹配#word#123#12_sdas,但不是1#234#1234

例如,在 中"#match1 notMatch not#Match #match2 notMatch #match3",只有#match1#match2#match3应该出现。

编辑:我只想要一磅 (#),然后是一个或多个 [a-ZA-Z0-9_]。比赛之前不能有任何 [a-ZA-Z0-9_]。

我的问题是在单词的开头找到英镑。

4

3 回答 3

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

编辑:没有 php cli 来测试这个,但正则表达式至少在 python 中工作。

于 2012-02-23T22:53:52.560 回答
1

试试这个:

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

它将匹配所有以#符号开头的单词。单词可以被所有有效的空白字符分隔(所以之一\t\r\n\v\f

例子

//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
        )

)
于 2012-02-23T22:54:37.577 回答
0

不确定php语法,但正则表达式应该像这样,使用单词边界和不区分大小写的第一个字母检查

/\b#[a-z]\w+\b/i

于 2012-02-23T23:49:14.523 回答