Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript RegExp: match, but don't capture

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?

like image 784
Adam Cook Avatar asked Sep 17 '14 16:09

Adam Cook


2 Answers

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.

like image 166
Niet the Dark Absol Avatar answered Sep 27 '22 22:09

Niet the Dark Absol


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.

like image 33
Jonny 5 Avatar answered Sep 27 '22 22:09

Jonny 5