-3

I need to write a regex that will allow 9 numbers and/or digits to be written in such format: XXX/XXX/XXX. However, the amount of them in each can vary, so for example it can be like: XX/XXXX/XXX as long as there are max 4 x's.

Tried my best but didn't come up with any solution.

abc def
  • 5
  • 1

2 Answers2

1

JavaScript based solution:

var input = prompt("Enter something");

var isValid = false;

if(/^\d{1,4}\/\d{1,4}\/\d{1,4}$/.test(input) && input.replace(/\//g, "").length == 9) {
  isValid = true;
}

console.log("Valid: ", isValid);

Explanation:

  1. \d denotes digits.
  2. Forward Slash / is a special character, hence it needs to be escaped, like \/
  3. You specify range with {0,4}
  4. After the pattern is verified, you have to strip out all the / from the input, and then compare length with 9
Abhijit Kar ツ
  • 1,732
  • 1
  • 11
  • 24
1

REGEX ONLY

(?=\b.{11}\b)[0-9]{1,4}\/[0-9]{1,4}\/[0-9]{1,4}
  • (?=\b.{11}\b) a positive lookahead asserting that you have exactly 11 char (because you have 9 digits and 2 slashes)
  • [0-9]{1,4} a group of minimum 1 and maximum 4 digits (you can use \d instead of 0-9)
  • \/ a slash escaped

Live demo here.

Don't forget to turn the g option on, which means that you don't return after the first match.

Francesco B.
  • 2,729
  • 4
  • 25
  • 37