Search code examples
javascriptregexword-boundary

regular expression @ character in word boundary


I am trying to extract words that starts with @ from a string

I created a simple regex using word boundary. But it is not finding matches when I try to find match words starts with @ character. I tried to escape character with \ but no use of it. Somebody please help me

const str='@alice wants to meet @bob'
console.log(str.match(/(\b@\S+\b)/ig))

Above code returns null


Solution

  • It sounds like you want to ensure that the location between the @ and the previous character is not a word boundary (since a word boundary would indicate that the previous character was a word character) - this can be matched with \B, which matches everywhere \b doesn't:

    const str='@alice wants to meet @bob foo@bar'
    console.log(str.match(/\B@\S+\b/ig))