mount a regular expression

Asked

Viewed 127 times

6

I would like a help from you to assemble an expression to check if there are more than 3 bars inside a url in javascript. example: http://exemplo.com , that he doesn’t take. http://exemplo.com/ola/, This he picks up. I will use the expression in the test method();

4 answers

11


Example of search of 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 above expression searches for the longest possible text, starting with a bar, ending with a bar and having at least 3 bars. Following the philosophy in @mgibsonbr’s commentary 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 = /\/.*?\/.*?\//;

Since the author of the question only wants to verify, with regular expression, whether the condition is true, this last expression is more appropriate.

  • 4

    Good answer. I would put the repeat operator no- Greedy efficiency (eg.: .*?), but it works one way or another.

8

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

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

If you don’t want to be with // then you can put two lines together to check that 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: http://jsfiddle.net/u6w0cx0n/

7

Follow 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);
    }

});

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');
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.