JavaScript RegExp: match but not capture

There are a thousand regular expression questions on SO, so I apologize if this is already covered. At first I watched.

Given the following pattern:

(?:/|-)[0-9]{2}$ 

And the following lines:

 str1 = '65/65/65' str2 = '65/65/6565' 

Matches:

 str1 = '/65' // expected '65' str2 = '' // as I expected 

My intention with ?: Should match, but not include / or - . Which correct regular expression matches my expectations?

+7
javascript regex
source share
3 answers

Since there are no objects available in Javascript, just wrap the desired part in a group:

 var str = '65/66/67'; if(res = str.match(/(?:\/|-)([0-9]{2})$/)) { console.log(res[1]); } 

See fiddle

Note: (?:\/|-) can be replaced with the symbol [\/-] , as @anubhava commented.

+5
source share

This is usually done using lookbehind:

 /(?<=[-\/])[0-9]{2}$/ 

Unfortunately, JavaScript does not support them.

Instead, since you know the length of the "extra bit" (that is, one character, either - , or / ), it should be simple enough to just .substr(1) it.

+1
source share

There is no appearance, but there is an exclusive match ( ?: , As this will not fail. The problem is that it will be included as part of the overall match (index 0 result). Therefore, the best alternative is to capture the part you want. In your example, this can be done by surrounding the matching numbers in parentheses.

 var re = /(?:[/-])([0-9]{2})$/, str1 = '12/34/56', str2 = '12/34/5678'; var res1 = str1.match(re); // will want to use res1[1], not res1[0] var res2 = str2.match(re); // null returned 
+1
source share

All Articles