0

I have a requirement in which I have a range of 2 IP addresses.

192.168.1.1-192.168.1.1

I want to check that whether both side of dash are valid IP addresses. For single IP address I have a regex but I am not able to add a '-' for checking 2.

Need some help. Below is single IP regex.

^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$
raju
  • 4,859
  • 11
  • 54
  • 108
  • 2
    Just add `-\1` at the end of your regex. `^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])-\1$` – Toto Sep 26 '19 at 11:42
  • @Toto That would require the *same* IP on both sides. – Niet the Dark Absol Sep 26 '19 at 11:43
  • @NiettheDarkAbsol: I understand they want same IP address – Toto Sep 26 '19 at 11:43
  • Both IP can be different, but should be valid IP having a '-' between them, basically it will be a string of 2 IP with '-' – raju Sep 26 '19 at 11:44
  • Then duplicate the same regex with an hyphen inbetween. `^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])-^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$$` – Toto Sep 26 '19 at 11:45
  • 1
    *I want to check that whether both side of dash are equal IP addresses.* - the answer is really `^(pattern here)-\1$`. Please edit the question if it is not the real problem. – Wiktor Stribiżew Sep 26 '19 at 11:46
  • @Toto: and tomorrow's assignment will be to validate three of them... or ten ;) – georg Sep 26 '19 at 11:47
  • @georg: May be, I just give here a solution for their specific problem. – Toto Sep 26 '19 at 11:48
  • Thanks everyone, you suggestions works, looks like this is working :: ^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])-(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$ – raju Sep 26 '19 at 11:50
  • Note you do not actually have to repeat the big pattern part, define it with a variable and build the regex dynamically, see [this answer](https://stackoverflow.com/a/50553431/3832970) – Wiktor Stribiżew Sep 26 '19 at 11:51
  • @georg, just asking on you comment, is it possible to have some generic solution in regex that take as many '-' between IPs – raju Sep 26 '19 at 11:52
  • **See [this answer](https://stackoverflow.com/a/50553431/3832970)**, that is an example of the generic solution. `^A(?:-A){0,Max-1}$` – Wiktor Stribiżew Sep 26 '19 at 11:52
  • @raju: glad you asked. In my opinion, regex is just the wrong tool for this job, because, as you can see, it's nothing but unreadable mess. What you can do instead is to write a short function that parses an IP into a number, and then compare these numbers anyway you want. – georg Sep 26 '19 at 11:56

0 Answers0