Cort3z Cort3z - 5 months ago 24
Javascript Question

How to write (A or B or C) followed by X in JavaScript regex?

I would like to match a string on the format:

"XYZ 1234.10"
//XYZ can be one of a relatively large, but defined, set of 3 uppercase letter combination.
//String must start with XYZ or other from allowed set
//1234 can be an integer of arbitrary length >= 0
//10 can be an arbitrary integer in the range 0-99, but must have string-length of 2. (eg. 00, 03, 82)
//String must end with .NN (dot, number, number) /\.\d\d$/

I have tried the following regex, but captures "XYZ" as well as "XYZ 1234.10":

var regex = /^(XYZ|ABC|QST) \d+\.\d\d$/
regex.exec("XYZ 1234.10")
// => ["XYZ 1234.10", "XYZ"] would like it to be ["XYZ 1234.10"]

I would like to get a match only on the full expression. I have not been able to find a way to express this with javascript regex.

Is this achievable at all? If so: how can it be done?

 // => ["XYZ 1234.10", "XYZ"] would like it to be ["XYZ 1234.10"]

exec is giving you the overall match followed by the contents of the capture groups. If you don't want the group to capture, make it a non-capturing group:

var regex = /^(?:XYZ|ABC|QST) \d+\.\d\d$/;
// ------------^^
console.log(regex.exec("XYZ 1234.10"));