Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 471
SimplGy Avatar asked Nov 25 '12 18:11

SimplGy


People also ask

How do you match everything after a word in regex?

If you want . to match really everything, including newlines, you need to enable "dot-matches-all" mode in your regex engine of choice (for example, add re. DOTALL flag in Python, or /s in PCRE.

How do you match a word exactly in regular expression?

But if you wish to match an exact word the more elegant way is to use '\b'. In this case following pattern will match the exact phrase'123456'.

How do I specify start and end in regex?

The caret ^ and dollar $ characters have special meaning in a regexp. They are called “anchors”. The caret ^ matches at the beginning of the text, and the dollar $ – at the end.

What matches the start of the string?

The meta character “^” matches the beginning of a particular string i.e. it matches the first character of the string.


1 Answers

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);
like image 71
Ωmega Avatar answered Oct 13 '22 19:10

Ωmega