Check IP adrress with regular expression

4 views (last 30 days)
Jacky
Jacky on 18 Apr 2014
Answered: Walter Roberson on 18 Apr 2014
Hi all,
I try to use regular expression to check the pattern of IP address, I tried with
IP = regexp(str, '[0-255]\.[0-255]\.[0-255]\.[0-255]', 'match')
but i can't work.
So, anyone know how to set the digit that range is from 0 to 255 to check the pattern of IP address? I tried with
IP = regexp(str, '[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?', 'match')
but it doesn't work for every situation.
Your suggestion and help is much appreciated. Thank you.

Answers (1)

Walter Roberson
Walter Roberson on 18 Apr 2014
0*
to allow leading 0's.
After that you can have
1\d\d
or
2[0-4]\d
or
25[0-4]
or
\d\d
or
\d
so take all those possibilities and join them with |
0*(1\d\d|2[0-4]\d|25[0-4]|\d\d|\d)
If you call that (say) Q, then your fuller pattern becomes
((Q\.){3}Q)
Then if necessary you would put guards around it to ensure that it was not proceeded or followed by a digit or a period

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!