本文介绍了Javascript正则表达式匹配字符串中以“#”开头的任何单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是正则表达式的新手。我试图在一个不包含换行符的字符串中匹配以'#'开头的任何单词(内容已经在换行符处拆分)。

I'm very new at regex. I'm trying to match any word that starts with '#' in a string that contains no newlines (content was already split at newlines).

示例(不工作) :

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' ]

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

I am trying to match any instance of '#', and grab the thing right after it, so long as there is at least one letter, number, or symbol following it. A space or a newline should end the match. The '#' should either start the string or be preceded by spaces.

这个PHP解决方案看起来不错,但它使用的是向后看的类型的功能,我不这样做知道JS正则表达式是否:

This PHP solution seems good, but it uses a look backwards type of functionality that I don't know if JS regex has:regexp keep/match any word that starts with a certain character

推荐答案

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

检查

Check this demo.

这篇关于Javascript正则表达式匹配字符串中以“#”开头的任何单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 20:00