1

I need to convert IP address into a regex expression in shell script.

Example Scenario: User will give the below as Input's, min Ip address value - 102.0.0.0 max Ip address value - 102.255.255.254

I am trying to generate the below regex as o/p to user using shell script.

Generated Regex: ^102.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5])).(([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-4])).([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))|255.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-4])))$

Note: Please note in most of the searches they have provided scripts to check if an IP address is valid or not. But my question is specifically intended to convert an IP address to regex using shell scripting.

  • There is a typo, it should be `[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]` for 0-255. –  Oct 25 '17 at 18:47
  • 4
    You'd probably be better off just splitting the numbers and using some basic math functions in your script than trying to validate the whole thing with a regex pattern. – CAustin Oct 25 '17 at 18:47
  • 1
    You need an algo to do this. It involves division by 10 and remainder. Unless you want to do something like that, I'd suggest you split on the periods and do the basic greater than and less than math thing. Example: 39-111 is `39|[4-9][0-9]|10[0-9]|11[0-1]` –  Oct 25 '17 at 18:49
  • @CAustin I am not trying to match regex function, my question is specifically intended to converted an IP address to regex using shell scripting. – Full - Stack - Developer Oct 25 '17 at 19:35
  • The real-life rules are more complex than this. In many applications, you cannot use the .0 or the network's broadcast address. – tripleee Oct 26 '17 at 03:44

0 Answers0