There are a thousand regular expression questions on SO, so I apologize if this is already covered. I did look first.
Given the following pattern:
(?:/|-)[0-9]{2}$
And the following strings:
str1 = '65/65/65'
str2 = '65/65/6565'
The matches are:
str1 = '/65' // expected '65'
str2 = '' // as I expected
My intention with ?: was to match, but not include a / or -. What is the correct regular expression to meet my expectations?
Normally, this would be done with a lookbehind:
/(?<=[-\/])[0-9]{2}$/
Sadly, JavaScript doesn't support those.
Instead, since you know the length of the "extra bit" (ie. one character, either -
or /
), it should be simple enough to just .substr(1)
it.
As there's no lookbehind available in Javascript, just wrap the desired part into a capturing group:
var str = '65/66/67';
if(res = str.match(/(?:\/|-)([0-9]{2})$/)) {
console.log(res[1]);
}
See fiddle
Note: (?:\/|-)
can be replaced with a character class [\/-]
like @anubhava commented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With