1

我是 regex 的新手,找不到轻松做到这一点的方法。我想删除不是以 # 开头的每个单词,并在它们之间加一个逗号,例如,如果我有:

Cookie Recipe for n00bs
#cookie #recipe #chocolate To do this you have to etc...
Bla bla bla mumbo jumbo

我想得到结果:

cookie, recipe, chocolate

如果你能帮助我,那就太好了,谢谢,祝你有美好的一天!

4

2 回答 2

0

你错过了告诉你正在使用哪种编程语言。下面是一个 PHP 示例,它使用 perl 兼容的正则表达式:

$text = <<<EOF
Cookie Recipe for n00bs
#cookie #recipe #chocolate To do this you have to etc...
Bla bla bla mumbo jumbo
EOF;

$pattern = '/((?<=#)\w+)/';
preg_match_all($pattern, $text, $matches);

echo implode(', ', $matches[0]);

我正在使用所谓的肯定后向断言(?<=#),它确保只匹配前面有 a 的单词#,这很重要,它不将#自身包含在匹配中。在lookbehind 表达式之后,我匹配尽可能多的单词字符\w

之后implode()用于将结果匹配与,. 正则表达式不能用于该部分工作。

你可以在Regex101.com看到这个正则表达式是如何工作的

于 2014-11-15T11:04:20.137 回答
0

试试这个:

$re = "/#\\w+/";
$str = "#cookie #recipe #chocolate To do this you have to etc...";
$str .= "#cookie #recipe #chocolate To do this you have to etc...";

preg_match_all($re, $str, $matches);
$r=@implode(", ",@$matches[0]);  // for adding comma(,) and space( ).
var_dump( $matches,$r);

输出:

array (size=1)
  0 => 
    array (size=6)
      0 => string '#cookie' (length=7)
      1 => string '#recipe' (length=7)
      2 => string '#chocolate' (length=10)
      3 => string '#cookie' (length=7)
      4 => string '#recipe' (length=7)
      5 => string '#chocolate' (length=10)

string '#cookie, #recipe, #chocolate, #cookie, #recipe, #chocolate' (length=58)

现场演示

于 2014-11-15T11:07:37.907 回答