const regex = /\d+[.\/]?\d+|\d+/g;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('\\d+[.\\\/]?\\d+|\\d+', 'g')
const str = `"47 g (0.25 cup)"
"47 g (0.25 cup)"
"56 g (0.5 cup)"
"40 g (0.25 cup)"
"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)"
`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions