Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Match a Particular set of string with regex

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading