2

I would like to make a regular expression for an IP address with asterisk(*) which matches these below:

The digit 127.0 could be any number between 0 to 255.

**[TRUE]**
127.*.*.*
127.0.*.*
127.0.0.*

**[FALSE]**
127.*.*.1
127.*.0.1
127.0.*.1

What I have made until now is...and of course, failed to make it out. I totally got lost..

_regex = function(value) {
    var _match = /^(?:(\d|1\d\d|2[0-4]\d|25[0-5]))\.(?:(\*|\d|1\d\d|2[0-4]\d|25[0-5]))\.(\*|(?:\d{1,2}(?:.\d{1,3}?)))\.(\*|(?:\d{1,3}(?:\*?)))$
    if(_match.test(value)){
        //do something;
    }
}

If you give me any chance to learn this, would be highly appreciated. Thanks.

3
  • var re = (? Regular expression literals need delimiters. Commented Jan 8, 2019 at 11:48
  • if(re.match(re)){ is wrong, use this if(value.match(re)){ Commented Jan 8, 2019 at 11:49
  • @ CertainPerformance @ÁlvaroTouzón Sorry for my mistake. I didn't copy my script and rushed to write this, so made many mistakes.. Commented Jan 8, 2019 at 11:52

1 Answer 1

2

I think what you are looking for is a negative look ahead to make sure no number follows an asterisk.

Like so: (\*(?!.*\d))

working example:

var ips = [
  '127.*.*.*',
  '127.0.*.*',
  '127.0.0.*',
  '127.*.*.1',
  '127.*.0.1',
  '127.0.*.1'
];

var regex = /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|(\*(?!.*\d)))(\.|$)){4}$/;

for(var i = 0; i < ips.length; i++){
  console.log(ips[i] + ': ' + regex.test(ips[i]));
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.