Th3Moron Th3Moron - 7 months ago 16
Javascript Question

JS Regex last two digits matches the first two digits

I'm new to regex, so please bare with my stupid question.

I've been trying to get this to work for a couple of hours now, and i still can't get i to work, as i want to.

What i need is, i have 4 number, and i need the last 2 numbers, to be the same as the first 2.

Like this would be a match:

1212
1313
1414


This in the other hand, should not be a match:

1513
1314
1236


I can't seem to get it to work, and i'm clueless on how to actually do it.

This is what i've got so far:

/^(?:(\d{2}))+$/g


Can i get some help, moving on? or a finger point in the right direction, on how to do it, or where to look it up, so i can find the answer my self.

Thanks in advance

Answer

You can use

/^(\d{2})\1$/

for 4 digit strings. See this regex demo.

var good_strs = ["1212", "1313", "1414"];
var bad_strs = ["1513", "1314", "1236"];
var res_good = good_strs.map(x => /^(\d{2})\1$/.test(x));
document.body.innerHTML = "Good string test:<pre>" + JSON.stringify(res_good, 0, 4) + "</pre>";
var res_bad = bad_strs.map(x => /^(\d{2})\1$/.test(x));
document.body.innerHTML += "Bad string test:<pre>" + JSON.stringify(res_bad, 0, 4) + "</pre>";

If there can be any characters in between, just insert [\s\S]* in between:

/^(\d{2})[\s\S]*\1$/

See another regex demo (lazy matching used for demo only).