10

我对正则表达式很陌生。我正在尝试匹配不包含换行符的字符串中以“#”开头的任何单词(内容已在换行符处拆分)。

示例(不工作):

var string = "#iPhone should be able to compl#te and #delete items"
var matches = string.match(/(?=[\s*#])\w+/g)
// Want matches to contain [ 'iPhone', 'delete' ]

我正在尝试匹配“#”的任何实例,并在它之后抓住它,只要它后面至少有一个字母、数字或符号。空格或换行符应该结束匹配。'#' 应该以字符串开头或以空格开头。

这个 PHP 解决方案看起来不错,但它使用了一种我不知道 JS 正则表达式是否具有的向后看类型的功能: regexp 保留/匹配任何以某个字符开头的单词

4

3 回答 3

14
var re = /(?:^|\W)#(\w+)(?!\w)/g, match, matches = [];
while (match = re.exec(s)) {
  matches.push(match[1]);
}

检查这个演示

let s = "#hallo, this is a test #john #doe",
  re = /(?:^|\W)#(\w+)(?!\w)/g,
  match, matches = [];

while (match = re.exec(s)) {
  matches.push(match[1]);
}

console.log(matches);

于 2012-11-25T18:51:14.023 回答
4

试试这个:

var matches = string.match(/#\w+/g);

let string = "#iPhone should be able to compl#te and #delete items",
  matches = string.match(/#\w+/g);

console.log(matches);

于 2012-11-25T18:50:27.900 回答
1

您实际上也需要匹配哈希。现在,您正在寻找紧跟在几个非单词字符之一的位置之后的单词字符。这失败了,原因很明显。试试这个:

string.match(/(?=[\s*#])[\s*#]\w+/g)

当然,前瞻现在是多余的,所以你不妨删除它:

string.match(/(^|\s)#(\w+)/g).map(function(v){return v.trim().substring(1);})

这将返回所需的:[ 'iPhone', 'delete' ]

这是一个演示:http: //jsfiddle.net/w3cCU/1/

于 2012-11-25T18:49:32.223 回答