[英]Javascript Regex match any word that starts with '#' in a string
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).
我正在尝试匹配不包含换行符的字符串中以“#”开头的任何单词(内容已在换行符处拆分)。
Example (not working):示例(不工作):
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.
'#' 应该是字符串的开头或前面有空格。
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这个 PHP 解决方案看起来不错,但它使用了一种我不知道 JS regex 是否具有的向后看类型的功能: 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]);
}
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);
Try this:试试这个:
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);
You actually need to match the hash too.您实际上也需要匹配哈希。 Right now you're looking for word characters that follow a position that is immediately followed by one of several characters that aren't word characters.
现在,您正在寻找紧跟某个位置的单词字符,该位置紧接着是几个非单词字符之一的字符。 This fails, for obvious reasons.
由于显而易见的原因,这失败了。 Try this instead:
试试这个:
string.match(/(?=[\s*#])[\s*#]\w+/g)
Of course, the lookahead is redundant now, so you might as well remove it:当然,lookahead 现在是多余的,所以你不妨删除它:
string.match(/(^|\s)#(\w+)/g).map(function(v){return v.trim().substring(1);})
This returns the desired: [ 'iPhone', 'delete' ]
这将返回所需的:
[ 'iPhone', 'delete' ]
Here is a demonstration: http://jsfiddle.net/w3cCU/1/这是一个演示:http: //jsfiddle.net/w3cCU/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.