Home > Mobile >  javascript regex group why do I get leading blanks?
javascript regex group why do I get leading blanks?

Time:05-18

When matching "product product name cat1" with this regex I get " product name" with a leading blank, of course I could trim in javascript but is there a way to modify regex to not catch that blank ?

(product)((\s )(.(?!cat1|cat2)) )

CodePudding user response:

Another way to look at it is to use a non greedy quantifier (.*?) in a single capture group, and match either cat1 or cat2 if you are only interested in product name

\bproduct\s (.*?)\s cat[12]\b

Regex demo

CodePudding user response:

You can use

(product)(\s )((?:(?!cat1|cat2).) )

See the regex demo.

Note:

  • Related