How to validate such input using a regular expression?

Viewed 95

Somebody's can help with this maybe by using regex. It is necessary for the "useInput" function to have minutes as the first parameter and seconds as the second parametr, if input can be: "1 2" (two digits - minutes seconds), "1" (just a digit - minutes), "1 minutes 2", "2 seconds 1 ".

Not so necessary but if is not too hard: seconds = sec = second = s; minutes = minute = min = m; Іnstead of "1 minutes" you can write "1 min" into "input"

const input = "   2   seconds   1   minutes   "
const regexTimer = new RegExp(/([0-9]+)\s*minutes?|([0-9]+)\s*seconds?/, 'g')

useInput(input.replace(regexTimer, '$1$2')).split(' '));//1 parameter is minute, 2 parametr is second 
       
function useInput(minutes, seconds){...};

1 Answers

You could use capture groups and pass those group values to the function.

Check which group values are not empty, and based on that pass the parameters in the right order to the function useInput.

For the partial names of seconds and minutes you can use nested optional groups.

^\s*(?:(\d+)(?:\s*(\d+))?|(\d+)(?:\s+s(?:ec(?:onds?)?)?)?(?:\s+(\d+)(?:\s+m(?:in(?:utes?)?)?)?)?|(\d+)(?:\s+m(?:in(?:utes?)?)?)?(?:\s+(\d+)(?:\s+s(?:ec(?:onds?)?)?)?)?)\s*$

Regex demo

const useInput = (minutes, seconds) =>
  console.log(`minutes: ${minutes ? minutes : "n/a"} - seconds: ${seconds ? seconds : "n/a"}`);
const regex = /^\s*(?:(\d+)(?:\s*(\d+))?|(\d+)(?:\s+s(?:ec(?:onds?)?)?)?(?:\s+(\d+)(?:\s+m(?:in(?:utes?)?)?)?)?|(\d+)(?:\s+m(?:in(?:utes?)?)?)?(?:\s+(\d+)(?:\s+s(?:ec(?:onds?)?)?)?)?)\s*$/;
[
  "1",
  "1 2",
  "1 minutes 2",
  "4 seconds 3",
  "5 seconds",
  "6 minutes",
  "7 min",
  "8 sec",
  "9 s 10 m",
  "11 m 12 second",
  "20 9 sec",
  "30 s 44",
  "test"
].forEach(s => {
  let m = s.match(regex);
  if (m) {
    if (m) {
      if (undefined !== m[1]) useInput(m[1], m[2])
      if (undefined !== m[3]) useInput(m[4], m[3])
      if (undefined !== m[5]) useInput(m[5], m[6])
    }
  }
})

Related