Javascript regex matches only words starting with a special special character

I am trying to combine only words starting with C # in javascript, for example. in the following text example, only #these should match.

I need to combine only words like #these. Ignore the ones that look like @ # this ,! #this and in # ignore.

The closer I got, the lower

/(\B(#[a-z0-9])\w+)/gi 

Link: https://regex101.com/r/wU7sQ0/114

+5
source share
4 answers

Use a space border (?:^|\s) :

 var rx = /(?:^|\s)(#[a-z0-9]\w*)/gi; var s = "I need to match only words like #these. \nIgnore the ones like @#this , !#this and in#ignore."; var m, res=[]; while (m = rx.exec(s)) { res.push(m[1]); } console.log(res); 

More details

  • (?:^|\s) - matches the beginning of a line or space
  • (#[a-z0-9]\w*) - Group 1 ( m[1] ): a # , then an alphanumeric char followed by 0 or more characters of the word (letters, numbers, _ ).

See the demo version of regex , pay attention to what texts will be captured, and not all matches.

Or trimming each match:

 var rx = /(?:^|\s)(#[a-z0-9]\w*)/gi; var s = "I need to match only words like #these. \nIgnore the ones like @#this , !#this and in#ignore."; var results = s.match(rx).map(function(x) {return x.trim();}); // ES5 // var results = s.match(rx).map(x => x.trim()); // ES6 console.log(results); 
+3
source

Why not start your search or from a place earlier. see regex / #|^#

+1
source

I slightly modified your regex to get what you need.

 var p = "I need to match only words like #these. Ignore the ones like @#this , !#this and in#ignore." [^@!az$]\#[az]+ 

This will only match #these, you can exclude anything you don't need by adding between the first square bracket

+1
source

you can try this

 txt = "I need to match only words like #these. Ignore the ones like @#this , !#this and in#ignore." console.log(/(^|\s)(#+\w+)/g.exec(txt)) 
0
source

Source: https://habr.com/ru/post/1270532/


All Articles