javascriptregex

How do I prevent a regex from matching every other match in javascript


I have the following regex that matches any number after a pound sign.

(^|\W)#(\d+)(\W|$)

I have the following text

#123321
#123321
#123321
#123321

Pasting this into http://regexpal.com/ note how the regex only matches every other #number. How do I make it so the regex matches each instance?


Solution

  • You need to use multiline flag:

    /(^|\W)#(\d+)($|\W)/mg
                        ^
    

    See demo

    The multiline flag forces ^ to match at the beginning of a line, and $ to match at the end of the line. It is also advised to place $ as the first element of the alternation, although in this case, it is not a big problem since you are only matching one \W.

    To enable the search of multiple values on one line, use a version of the regex with a loof-ahead:

    /(^|\W)#(\d+)(?=$|\W)/mg
                 ^------^
    

    Or even shorter:

    /(^|\W)#(\d+)(?!\w)/mg
    

    See another demo

    The lookahead will not consume characters, it will just check for the end-of-line or a non-word character presence after the digits, and then it will be able to check the same character during the next iteration.