const regex = /(?<!\w)\b(?:(?<hour_digit>\d+)(?:\s*(?:more|another))?\s*hours?)?(?:(?:\s*(?:or|up to|and|to))*\s*(?<minute_digit>\d+)(?:\s*(?:more|another))?\s*minutes?)?(?:(?:\s*(?:or|up to|and|to))*\h*(?<second_digit>\d+)(?:\s*(?:more|another))?\s*seconds?)?\b(?!\w)/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?<!\\w)\\b(?:(?<hour_digit>\\d+)(?:\\s*(?:more|another))?\\s*hours?)?(?:(?:\\s*(?:or|up to|and|to))*\\s*(?<minute_digit>\\d+)(?:\\s*(?:more|another))?\\s*minutes?)?(?:(?:\\s*(?:or|up to|and|to))*\\h*(?<second_digit>\\d+)(?:\\s*(?:more|another))?\\s*seconds?)?\\b(?!\\w)', 'gm')
const str = `1 second
21 seconds
1 minutes
21 minutes
1 hour
11 hours
2 more seconds
1 more second
12 more minutes
21 more hours
11 hours
5 hours 5 minutes to 6 hours 6 minutes
7 hours 7 minutes
9 hours or up to 10 hours
5 hours and 15 minutes
For the first step, wash the clothes for 15 minutes. While the clothes are washing, hold your breath for up to 5 minutes.`;
// 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