Home > database >  Match a Particular set of string with regex
Match a Particular set of string with regex

Time:09-07

I am trying to match a particular set of strings with a regex

1- #1 – .75 Gallon $16.99

2- #2 –1.6 Gallon $36.99

This is what I tried to figure out with many attempts but still it doesn't seems to work

console.log(/^#\d\s –\s [0-9]*\.[0-9] \s [a-zA-Z] \s :[0-9]*\.[0-9] $/.test('#2 – 1.6 Gallon $36.99'))

console.log(/^#\d\s –\s [0-9]*\.[0-9] \s [a-zA-Z] \s :[0-9]*\.[0-9] $/.test('#1 – .75 Gallon $16.99'))

I have gone through each part individually but I don't know where I am making mistake ,any help would be really appreciated. Thanks

CodePudding user response:

You should allow any (even zero) amount of whitespaces around the hyphen, and you need to match a dollar symbol instead of a colon:

^#\d\s*–\s*\d*\.?\d \s [a-zA-Z] \s \$\d*\.?\d $

See the regex demo.

I also added a ? quantifier after \. to match integers.

Details:

  • ^ - start of string
  • # - a # char
  • \d - a digit
  • \s*–\s* - a hyphen wrapped with zero or more whitespaces
  • \d*\.?\d - an integer or float like value: zero or more digits, an optional . and then one or more digits
  • \s - one or more whitespaces
  • [a-zA-Z] - one or more letters
  • \s - one or more whitespaces
  • \$ - a $ char
  • \d*\.?\d - an integer or float like value
  • $ - end of string.
  • Related