user2144099
user2144099

Reputation: 33

Regex to match an IP range?

Can someone help me with a regular expression to match a range of IPs. It should match something like this:

"203.0.113.0-203.0.113.255"

I tried the following but that only matches for a single IP:

((?:\\d{1,3}\\.){3}\\d{1,3})(?:/((?:(?:\\d{1,3}\\.){3}\\d{1,3})|\\d{1,2}))?

Upvotes: 0

Views: 6323

Answers (5)

raven
raven

Reputation: 43

You can generate a regex for an IP Range in this page https://www.analyticsmarket.com/freetools/ipregex/

For your case,the generated regex is ^203\.0\.113\.([1-9]?\d|[12]\d\d)$ for IP Addresses within the range 203.0.113.0 to 203.0.113.255

Upvotes: 0

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

Try this out :

String data = "This http://example.com is a sentence 203.0.113.0-203.0.113.255 https://secure.whatever.org that contains 2 URLs.";


    Pattern pattern = Pattern.compile("\\s((\\d{1,4}\\.?){4}-(\\d{1,4}\\.?){4})\\s");
    Matcher matcher = pattern.matcher(data);

    while (matcher.find()) {
        System.out.println(matcher.group(1));
    }

Hope this helps.

Upvotes: 0

Pshemo
Pshemo

Reputation: 124215

If you have regex that will match single IP then just add - and repeat your regex

String singleIPRegex = "yourRegex";
String rangeRegex = singleIPRegex + "-" + singleIPRegex;

if (someString.matches(rangeRegex)){
    //do your stuff
}

Also as singleIPRegex you can use

(([01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d{1,2}|2[0-4]\\d|25[0-5])

part

([01]?\\d{1,2}|2[0-4]\\d|25[0-5])

will accept:

  • [01]?\\d{1,2} -> range 0-199 including numbers started with 0 or 00 like 01, 001
  • 2[0-4]\\d -> range 200-249
  • 25[0-5] -> range 250-255

Upvotes: 0

VishalDevgire
VishalDevgire

Reputation: 4268

Try this : ((?:\d{1,3}\.){3}\d{1,3})(?:/((?:(?:\d{1,3}\.){3}\d{1,3})|\d{1,2})){2}

Upvotes: 0

iberbeu
iberbeu

Reputation: 16185

You can split the String in 2 components

String[] splitResult = ipRange.split("-");

and then use this pattern for each substring

string pattern = @"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"

Your pattern will actually not work, due to the fact that each IP section only goes up to 255

Upvotes: 2

Related Questions