Javascript Regex匹配字符串中以“#”开头的任何单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13554208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Regex match any word that starts with '#' in a string
提问by SimplGy
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 正则表达式是否具有: regexp 保留/匹配以某个字符开头的任何单词
采纳答案by ?mega
回答by vaidik
Try this:
试试这个:
var matches = string.match(/#\w+/g);
回答by Asad Saeeduddin
You actually need to match the hash too. Right now you're looking for word characters that follow a positionthat 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:
当然,现在前瞻是多余的,所以你不妨删除它:
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/