mount a regular expression

6

I would like some help from you to put together an expression to check if there are more than 3 bars inside a url in javascript. example: link , this one it does not catch. link , This one it catches. I will use the expression in the test () method;

    
asked by anonymous 13.10.2015 / 06:29

4 answers

11

Example search for at least 3 bars:

var expr = /\/(.*\/){2,}/;

alert(expr.test('http://exemplo.com')); // exibe false
alert(expr.test('http://exemplo.com/ola/')); // exibe true

This expression looks for a text with 3 bars with any number of characters between them (including none).

Editing: The expression above searches for the most extensive text possible, starting with a slash, ending with a slash and having at least 3 slashes. Following the philosophy in the comment of @mgibsonbr of better efficiency, which I agree, a more restrictive expression with less processing, finds only the first three bars with the fewest possible number of characters between them would be:

var expr = /\/.*?\/.*?\//;

As the questioner just wants to check, with regular expression, if the condition is true, the latter expression is more appropriate indeed.

    
13.10.2015 / 07:20
8

If you want to check whether there is or is not, then you do not need regex. You can use the split which is faster.

function tem3Barras(url){
    return url.split('/').length > 3;
}

If you do not want to start with // then you can join two lines to check this and separate that part.

function tem3Barras(url){
    var doubleBar = url.indexOf('//');
    if (doubleBar != -1) url = url.slice(doubleBar + 2);
    return url.split('/').length > 2;
}

jsFiddle: link

    
13.10.2015 / 08:50
7

Here's an example:

var array = [
    'http://exemplo.com',
    'http://exemplo.com/ola',
    'http://exemplo.com/ola/',
    'www.exemplo.com/ola/mundo/javascript',
    'www.exemplo.com/ola/mundo/javascript/'
];

array.forEach(function (elm) {

    if (elm.match(new RegExp('\/', 'g')).length > 3) {
        console.dir('possui mais de 3 barras: ' + elm);
    }

});
    
13.10.2015 / 07:07
3

Here's a simple way to do a validation:

function checkBars(url) {
  if (url.indexOf('/') !== -1) {
     if (url.split('/').length > 3) {
        return true;      
     }
  }
return false;
}

if (checkBars('http://www.pt.stackoverflow.com/questions/91990/montar-uma-expressão-regular/92057')) {
  alert('possui mais de 3 barras');
} else {
  alert('possui menos de 3 barras');
}
    
13.10.2015 / 15:55