简体   繁体   中英

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

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

Check this demo .

 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:

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM