2

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

1 Answers1

2

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.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Thanks a lot :) ,just one small thing i don't want the value $16.99 ,the value after $ to not be greater than 1000 ,how can i do that .please if you can tell. – Samaha Hcndcl Sep 06 '22 at 13:09
  • You will need to replace `\d*\.?\d+` with `(?:\d|[1-9]\d{1,2})(?:\.\d+)?`. This matches a number from `0` to `999` (see [here](https://stackoverflow.com/a/67502416/3832970) how to generate such patterns). – Wiktor Stribiżew Sep 06 '22 at 13:12