Reputation: 20437
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
Upvotes: 13
Views: 29490
Reputation: 2213
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);
Upvotes: 4
Reputation: 43673
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);
Upvotes: 15
Reputation:
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/
Upvotes: 1