I want to extract the numbers and words from a string into a serving_unit array and a serving_size array.
For example:
"56 g (0.5 cup)" would create serving_size_array=[56 , 0.5] & serving_unit_array=["g", "cup"]
or
"1 ARTICHOKE, EDIBLE (120 g)" would create serving_size_array=[1, 120] & serving_unit_array=["ARTICHOKE, EDIBLE", "g"]
some easy sample values:
"47 g (0.25 cup)"
"47 g (0.25 cup)"
"56 g (0.5 cup)"
"40 g (0.25 cup)"
some not-so-easy sample values:
"2 SLICES (57 g)"
"3.0g"
"serving"
"1 ARTICHOKE, EDIBLE (120 g)"
"1/4 pizza (133 g)"
"1 pizza 52 g"
"42 g (0.5 DRY NOODLE BLOCK AND 1 TSP SEASONING MIX | ABOUT)"
"4 COOKIES, PER CONTAINER ABOUT (15 g)"
"15 ASSORTED NUTS | APPROX. (30 g)"
"Per 1 piece (1.9 g)"
"1 piece (1.9 g) (1.9 g)"
I am using javascript for this. Any help would be very much appreciated!
CodePudding user response:
I'm < 1 year into my Full Stack Development journey. In the tech test of my first job there were 3 (THREE!!) Regex questions.
Assuming all items you need to get access too come following serving_unit_array, I can recommend some resources to learn/ play with Regex:
You can do it!
CodePudding user response:
The numbers are easy if you know they're always going to be in the same format, but the units are much harder because the location or format isn't fixed.
For the numbers you could use the following:
(?:\d \/\d )|(?:\d (?:\.\d )?)
with:
- The first group
(?:\d \/\d )
matches fractions such as 1/4 - The second group
(?:\d (?:\.\d )?)
matches integers or decimals
Regex 101 link to try it out.
CodePudding user response:
It is really very simple:
For number: https://regex101.com/r/DsAlRS/1
For string: https://regex101.com/r/HbgA0T/1
Good luck !