1

I want to test whether a string is 8 digits or the same number can be divided into 4 parts separated by a -.

I have a regex that does work:

/^\d{2}([-]?)(\d{2})\1\d{2}\1\d{2}$/

And I can prove:

/^\d{2}([-]?)(\d{2})\1\d{2}\1\d{2}$/.test('12345678'); // true
/^\d{2}([-]?)(\d{2})\1\d{2}\1\d{2}$/.test('12-34-56-78');  // true
/^\d{2}([-]?)(\d{2})\1\d{2}\1\d{2}$/.test('12-45-7810'); // false
/^\d{2}([-]?)(\d{2})\1\d{2}\1\d{2}$/.text('-12-45-78-10'); //false

I would have liked to have created a group from \d{2} but I tried this:

/^(\d{2})([-]?)\1\2\1\2\1$/

But it does not match anything.

5
  • It does match something: try "22-22-22-22". By using \1 it only matches the exact same two digits. Commented May 27, 2018 at 13:23
  • \1 will match exactly the same text, not the variables. If you have 12121212 it will probably match it Commented May 27, 2018 at 13:25
  • 1
    Note that ^(\d{2}-\d{2}-\d{2}-\d{2}|\d{8})$ works just fine Commented May 27, 2018 at 13:33
  • Things like (?n) / \g<n> (subroutines) are not supported in JS RegExp. See this JSFiddle to get a hint on how to get what you need. Commented May 27, 2018 at 14:21
  • Did my solution help? Commented Nov 22, 2018 at 9:33

3 Answers 3

1

You can write even shorter: ^\d\d(-\d\d){3}$|^\d{8}$

Sign up to request clarification or add additional context in comments.

Comments

1

You cannot make backrefernces (references to actual values captured with group patterns) work as subroutines (constructs "repeating" some group patterns, not the actual captured values).

You can only define pattern parts and use them to build longer patterns:

const n = "\\d{2}";
const h = "-?";
const rx = new RegExp(`^${n}(?:${h}${n}){3}$`);
console.log(rx.source); // ^\d{2}(?:-?\d{2}){3}$
// ES5:
// var rx = new RegExp("^" + n + "(?:" + h + n+ "){3}$");
 
const strs = ['12345678', '12-34-56-78', '12-45-7810', '-12-45-78-10'];
for (let s of strs) {
	console.log(s, "=>", rx.test(s));
}

Comments

0

Have you tried:

const r = new RegExp(/^-?\d{2}-?\d{2}-?\d{2}-?\d{2}$/);
console.log(r.test("12345678")); // true
console.log(r.test("12-34-56-78")); // true
console.log(r.test("12-45-7810")); // true
console.log(r.test("-12-45-78-10")); // true

This works on my end.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.