Javascript Regex match any word that starts with &

2020-02-09 11:35发布

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

3条回答
放荡不羁爱自由
2楼-- · 2020-02-09 12:13

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:

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

This returns the desired: [ 'iPhone', 'delete' ]

Here is a demonstration: http://jsfiddle.net/w3cCU/1/

查看更多
【Aperson】
3楼-- · 2020-02-09 12:23
var re = /(?:^|\W)#(\w+)(?!\w)/g, match, matches = [];
while (match = re.exec(s)) {
  matches.push(match[1]);
}

Check this demo.

查看更多
▲ chillily
4楼-- · 2020-02-09 12:30

Try this:

var matches = string.match(/#\w+/g);
查看更多
登录 后发表回答