Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex optional character

I have a regex pattern that I'm using (got it from Stack Overflow) to extract a video ID from a vimeo URL:

var regExp = /http:\/\/(www\.)?vimeo.com\/(\d+)($|\/)/;     var match = url.match(regExp); 

I need it to work whether http or https is specified. I've tried

var regExp = /http(s)?:\/\/(www\.)?vimeo.com\/(\d+)($|\/)/; 

But this fails on both http and https.

Help a brother out.

like image 500
Fraser Avatar asked Oct 24 '13 15:10

Fraser


People also ask

How do you make a string optional in regex?

Adding ? after the non-capturing group makes the whole non-capturing group optional. Alternatively, you could do: \".

What is preceding token in regex?

asterisk or star ( * ) - matches the preceding token zero or more times. For example, the regular expression ' to* ' would match words containing the letter 't' and strings such as 'it', 'to' and 'too', because the preceding token is the single character 'o', which can appear zero times in a matching expression.


1 Answers

It fails because you are creating an extra capturing group, meaning that the capturing group indexes will not be the same as before.

To make the s optionnal without creating a capturing group, you can simply add ?, you do not need the parenthesis.

/https?:\/\/(www\.)?vimeo.com\/(\d+)($|\/)/ 

To create a non-capturing group, you can use (?:), but that's not necessary here, just showing for the example:

/http(?:s)?:\/\/(www\.)?vimeo.com\/(\d+)($|\/)/ 
like image 158
plalx Avatar answered Sep 21 '22 10:09

plalx