Jump to content

Looking for a relatively simple method to create regex patterns to detect a number range


 Share

Go to solution Solved by Morthawt,

Recommended Posts

I am writing a program that can take a CIDR network like 192.168.0.0/16 and turn it into a regular expression which will detect any IP in the range. Also since the info being passed to the function is a valid CIDR network, there is no need to sanitize the input to ensure it is an IP address, because it is.

I am working on this idea currently. I have managed to translate the CIDR to a start and end IP of which both address' octets are stored in it's array's elements so that I can easily access just the number content for both start and end of the same octet.

The problem is this is extremely complicated the way I am doing it. I simplify things by just dealing with two numbers, since each octet is just a start number and an end number. Then I am dealing with it if both numbers are a single digit, that works fine. I just completed if both numbers are 2 digits and that works. Now I am about to try and do if both numbers are 3 digits but I am struggling... Then once I magically am able to figure this 3 digit thing out I have to accommodate for both numbers being of dissimilar digit counts.

Is there a method that you can explain to help me make a relatively elegant piece of script that can detect numbers inside ranges such as:

1-5

1-99

10-199

108-255

If there is a simpler method than I am attempting to do I would be very appreciative, especially if it is a method I can understand and implement.

Here is what I have so far (the part which stars with $regex = '^' is the part I am working on, from that point onward, the previous code works fine for what I need. 

;~ $CIDR = '104.131.192.0/19' ; 104.131.192.1 - 104.131.223.255
$CIDR = '192.168.12.0/22' ; 192.168.12.1 - 192.168.15.254
;~ $CIDR = '192.168.0.10/31' ; 192.168.0.10 - 192.168.0.11
$CIDR = '192.168.17.0/20'

RegexIP($CIDR)
If @error Then ConsoleWrite('ERROR' & @CRLF)


Func RegexIP($_CIDRNet)
    $slashPos = StringInStr($CIDR, '/')
    $networkNumber = StringMid($CIDR, $slashPos + 1, StringLen($CIDR) - $slashPos)
    $networkRemainder = 32 - $networkNumber
    Local $LastIP[4]
    $FirstIP = StringSplit($CIDR, '.', 3)
    $FirstIP[3] = StringReplace($FirstIP[3], '/' & $networkNumber, '')

    $binpos = 128
    $bintotal = 0
    $currentOctet = 0
    $deductamount = 0
    For $a = 1 To 32
        If $a > $networkNumber Then
            $deductamount += $binpos
        EndIf

        $binpos /= 2
        If IsInt($a / 8) Then
            $LastIP[$currentOctet] = $FirstIP[$currentOctet] + $deductamount
            If $LastIP[$currentOctet] > 255 Then
                Return SetError(1, 0, 0)
            EndIf
            $deductamount = 0
            $binpos = 128
            $currentOctet += 1
        EndIf
    Next

;~  For $a = 0 To 3
;~      ConsoleWrite($FirstIP[$a] & (($a = 3) ? (' - ') : ('.')))
;~  Next

;~  For $a = 0 To 3
;~      ConsoleWrite($LastIP[$a] & (($a = 3) ? (@CRLF) : ('.')))
;~  Next



    ;;;;;;; FORCED IP's TO HELP DESIGN AND TEST THE REGEX GENERATOR FEATURE
    $FirstIP[0] = 192
    $FirstIP[1] = 168
    $FirstIP[2] = 0
    $FirstIP[3] = 100

    $LastIP[0] = 192
    $LastIP[1] = 168
    $LastIP[2] = 0
    $LastIP[3] = 200
    ;;;;;;; FORCED IP's TO HELP DESIGN AND TEST THE REGEX GENERATOR FEATURE


    $regex = '^'

    For $a = 0 To 3
        If $FirstIP[$a] = $LastIP[$a] Then
            $regex &= $LastIP[$a]
            $regex &= (($a = 3) ? ('$') : ('\.'))
            ContinueLoop
        EndIf

        ; Both start & end have 1 digit
        If StringLen($FirstIP[$a]) = 1 And StringLen($LastIP[$a]) = 1 Then
            If $LastIP[$a] - $FirstIP[$a] > 1 Then ; If the difference between them is more than 2 eg not 2 - 3
                $regex &= '[' & $FirstIP[$a] & '-' & $LastIP[$a] & ']'
            Else
                $regex &= '[' & $FirstIP[$a] & $LastIP[$a] & ']'
            EndIf
        EndIf

        ; Both start & end have 2 digit
        If StringLen($FirstIP[$a]) = 2 And StringLen($LastIP[$a]) = 2 Then

            If StringMid($FirstIP[$a], 1, 1) = StringMid($LastIP[$a], 1, 1) Then ; If both first digits are the same eg 12 - 13
                $regex &= StringMid($FirstIP[$a], 1, 1) & '(' ; eg 1(

                If StringMid($LastIP[$a], 2, 1) - StringMid($FirstIP[$a], 2, 1) > 1 Then ; If the difference between them is more than 2 eg not 2 - 3
                    $regex &= '[' & StringMid($FirstIP[$a], 2, 1) & '-' & StringMid($LastIP[$a], 2, 1) & '])'
                Else
                    $regex &= '[' & StringMid($FirstIP[$a], 2, 1) & StringMid($LastIP[$a], 2, 1) & '])'
                EndIf


            Else ; First digits are not the same eg 17 - 20
                $regex &= '(' & StringMid($FirstIP[$a], 1, 1)
                If StringMid($FirstIP[$a], 2, 1) <> 0 Then ; Start octet's last digit doesn't start from fresh eg 17
                    $regex &= '[' & StringMid($FirstIP[$a], 2, 1) & ((9 - StringMid($LastIP[$a], 2, 1) > 1) ? ('-' & 9) : (9))
                Else
                    $regex &= '[' & 0 & '-' & 9
                EndIf
                $regex &= ']|'
                If StringMid($LastIP[$a], 1, 1) - StringMid($FirstIP[$a], 1, 1) > 1 Then ; The gap between start and end initial number is more than 1 eg 17 - 32

                    If StringMid($LastIP[$a], 2, 1) <> 9 Then ; If the last digit of the end point is not 9 eg 17 - 32
                        $regex &= '[' & StringMid($FirstIP[$a], 1, 1) + 1 & '-' & StringMid($LastIP[$a], 1, 1) - 1 & '][0-9]|'
                        $regex &= StringMid($LastIP[$a], 1, 1) & '[0-' & StringMid($LastIP[$a], 2, 1) & '])'
                    Else
                        $regex &= '[' & StringMid($FirstIP[$a], 1, 1) + 1 & '-' & StringMid($LastIP[$a], 1, 1) - 1 & '][0-9]|'
                        $regex &= StringMid($LastIP[$a], 1, 1) & '[0-9])'

                    EndIf

                Else ; The gap between start and end initial number is only 1 eg 17 - 22

                    If StringMid($LastIP[$a], 2, 1) <> 9 Then ; If the last digit of the end point is not 9 eg 17 - 22
                        $regex &= StringMid($LastIP[$a], 1, 1) & '[0-' & StringMid($LastIP[$a], 2, 1) & '])'
                    Else
                        $regex &= StringMid($LastIP[$a], 1, 1) & '[0-9])'

                    EndIf

                EndIf


            EndIf



        EndIf



        If StringLen($FirstIP[$a]) = 3 And StringLen($LastIP[$a]) = 3 Then ; If both start and end octets have 3 digits








        EndIf








        $regex &= (($a = 3) ? ('$') : ('\.'))
        ConsoleWrite(RegexCleanup($regex) & @CRLF)
    Next

EndFunc   ;==>RegexIP

Func RegexCleanup($_input)

    For $a = 0 To 9
        $_input = StringReplace($_input, '[' & $a & '-' & $a & ']', $a)
        If $a < 9 Then
            $_input = StringReplace($_input, '[' & $a & '-' & $a + 1 & ']', '[' & $a & $a + 1 & ']')
        EndIf
    Next

    Return $_input
EndFunc   ;==>RegexCleanup

I realise this code is messy, but I am just wondering if someone can explain a methodology or technique which will help me to make script that can generate a simple block of regular expression to match a range of numbers from between 1 and 3 digits which I can compile into a full length IP regex like I can manually such as ^192.168.(9[6-9]|1[0-1][0-9]|12[0-7]).[0-9]+$

Edited by Morthawt
Link to comment
Share on other sites

  • Replies 41
  • Created
  • Last Reply

Top Posters In This Topic

Top Posters In This Topic

Are you going to process IPv4 only or IPv6 as well?

In the former case, then why not converting the (valid) base address to integer and the top address with stuffing binary ones with OR. Then a simple "between test" with IP addresses to test converted to uint32 will work. This will be much simpler than a painful regexp.

In the latter case, IPv6 addresses and blocks input formats are more complex but can still use the same technique but with uint64 this time.

I'd use an union of DllStruct to set bits along with uint32 or -64 to read them off.

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

Are you going to process IPv4 only or IPv6 as well?

In the former case, then why not converting the (valid) base address to integer and the top address with stuffing binary ones with OR. Then a simple "between test" with IP addresses to test converted to uint32 will work. This will be much simpler than a painful regexp.

In the latter case, IPv6 addresses and blocks input formats are more complex but can still use the same technique but with uint64 this time.

I'd use an union of DllStruct to set bits along with uint32 or -64 to read them off.

Getting into DLL things is beyond me, aside from _ispressed. I need to produce regular expressions in the format in my example for use on TeamSpeak. So I must have that type of output. I am not sure what exactly you are saying, could you elaborate so that I understand how I could proceed with your alternative method if it does not require messing with dll's? I am currently trying another method I came up with but this is just as slow going as the previous one.

Link to comment
Share on other sites

Wow. I have no idea what the code is doing. I only feel comfortable use code I fully understand so that I can support/update my own code when a new version of AutoIt breaks it, since I full understand it I have a far higher chance of resolving some kind of problem. That is why I pretty much never ever use external UDF because most of the time people are doing what I consider to be rocket science things with their script, which is a big "wow" and a turn-off at the same time.

Link to comment
Share on other sites

I assure you it's not brain surgery, it's just some maths, which I am lousy at.

Take a little more than 60 seconds and you should see it's quite simple.

 

Ok, well I understand the principle, although I do not understand the workings of the math. But assuming I find my own method of turning the two IP's (start and end IP's) how would I use that to help me generate the regular expression code? I already have each octet broken down so I can compare each octet from the start and end IP addresses. My problem is actually generating regular expression code.

Link to comment
Share on other sites

I'm not sure I follow about the term "Generate Regex Code" regex it s pattern the developer creates is it not?

If you convert the start IP to inr and the end IP to int, you only need to test if any subsequent converted IP is between those two numbers.

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Link to comment
Share on other sites

I'm not sure I follow about the term "Generate Regex Code" regex it s pattern the developer creates is it not?

If you convert the start IP to inr and the end IP to int, you only need to test if any subsequent converted IP is between those two numbers.

 

the purpose of my program is to generate regular expression code which will match a range of IP addresses. The regex will be used in TeamSpeak, so the string checked against the regex is an IP and thus does not need checking for formatting/validity etc. So per octet for the start and end I end up with a minimum and maximum and then need to generate regex code for each octet. So for example Start IP 192.168.0.1 End IP 192.168.125.255 I take the first octet that changes and end up with a minimum of 0 and a maximum of 125, so now I need to make my program generate a regex like:

([0-9]|[0-9][0-9]|1([0-1][0-9]|2[0-5]))

Then for each octet worth of regex, it constructs the full regex such as you can see one example below (not the same as the example IP's I gave above:

^146.185.(12[8-9]|1[3-5][0-9]).[0-9]+$

Link to comment
Share on other sites

Would you like to check if a given IP address is within the range given by an IP/cidr?
something like this?

$start = "192.168.000.001"
$end = "192.168.255.254"
$check = "192.168.111.254"

MsgBox(0, "Check", "Belongs: " & IP_Belongs($start, $end, $check))

Func IP_Belongs($start, $end, $check)
    Return (IpToNum($check) >= IpToNum($start)) And (IpToNum($check) <= IpToNum($end))
EndFunc   ;==>IP_Belongs

Func IpToNum($ip)
    Return Number(StringReplace($ip, ".", ""))
EndFunc   ;==>IpToNum

or would you like to generate all IP addresses given by an IP/Cidr?

edit:

or none of those.....

Edited by Chimp

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Link to comment
Share on other sites

Is this what you are looking for...

local $sIPRange = '192.1.68.7/200'

local $aQ4 = stringsplit(stringregexpreplace($sIPRange,'.*\.(\d+)','\1'),'/')

local $SRE = '\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:'

for $1 = $aQ4[1] to $aQ4[2]
    $SRE &= $1 & '|'
Next

$SRE = stringtrimright($SRE,1) & ")$"

; test SRE
local $aIP = ['192.1.68.32','192.1.68.255','199.0.0.3','192.1.0.15']
for $1 = 0 to ubound($aIP) - 1
    ConsoleWrite('IP address ' & $aIP[$1] & (stringregexp($aIP[$1],$SRE) ? ' is valid' & @CRLF : ' is not valid' & @CRLF))
next

kylomas (confused and curious about your issue)

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Link to comment
Share on other sites

Would you like to check if a given IP address is within the range given by an IP/cidr?

something like this?

$start = "192.168.000.001"
$end = "192.168.255.254"
$check = "192.168.111.254"

MsgBox(0, "Check", "Belongs: " & IP_Belongs($start, $end, $check))

Func IP_Belongs($start, $end, $check)
    Return (IpToNum($check) >= IpToNum($start)) And (IpToNum($check) <= IpToNum($end))
EndFunc   ;==>IP_Belongs

Func IpToNum($ip)
    Return Number(StringReplace($ip, ".", ""))
EndFunc   ;==>IpToNum

or would you like to generate all IP addresses given by an IP/Cidr?

edit:

or none of those.....

No I am not trying to see if something is within the scope, I am literally trying to only have the script create a regex pattern for each octet which can be combined to create a final single regex pattern which encompasses the entire IP range which can be used in another program.

Link to comment
Share on other sites

Is this what you are looking for...

local $sIPRange = '192.1.68.7/200'

local $aQ4 = stringsplit(stringregexpreplace($sIPRange,'.*\.(\d+)','\1'),'/')

local $SRE = '\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:'

for $1 = $aQ4[1] to $aQ4[2]
    $SRE &= $1 & '|'
Next

$SRE = stringtrimright($SRE,1) & ")$"

; test SRE
local $aIP = ['192.1.68.32','192.1.68.255','199.0.0.3','192.1.0.15']
for $1 = 0 to ubound($aIP) - 1
    ConsoleWrite('IP address ' & $aIP[$1] & (stringregexp($aIP[$1],$SRE) ? ' is valid' & @CRLF : ' is not valid' & @CRLF))
next

kylomas (confused and curious about your issue)

No this is not what I am trying to achieve. I really do not know how else to explain it. I am trying to write a script that generates regular expressions for an IP range... So I put in a CIDR network which may look like 192.168.0.0/16 and after the processing is done in the script, it will spit out a result that looks like this (this example is not based on the CIDR network I pasted, this is a real example that I have made manually) ^64.237.(3[2-9]|[45][0-9]|6[0-3]).[0-9]+$

I was hoping for some elegant, simple principle someone could explain how to pull it off but so far it is not looking good. I have so far started from scratch, at least in terms of performing the regex operation, and I have gotten it to the point where I can make correct regex patterns for 1-2 digit numbers. I am now going to need to work on making digits up to 3 work, but it may be more difficult now at this stage. My new technique is simpler than the original convoluted one, but still it is extremely complicated and taxing for me to work out.

Edited by Morthawt
Link to comment
Share on other sites

ok
I'm really out of the games with regex,
but if it can be useful, here is an extract of an udf I made time ago, that generates lan parameters that maybe can came handy for your purpose...
perhaps the function _Make_Range() ?

#include <array.au3>
 _LanParameters("192.168.0.0", 16, 1) ; pass IP, CIDR, [showresults true/false]
 
 MsgBox(0,"Range:",_Make_Range("192.168.0.0",16))  ; pass IP, CIDR
 
$xx = _GetLanParameters("192.168.0.0",16) ;  ; pass IP, CIDR
_ArrayDisplay($xx)

; = = = = = net related functions = = = = =
Func _Make_Range($ipLan, $sMask) ; Given an IP and his mask, this function return the full LAN "range" for _nPing
    Local $aLan = _GetLanParameters($ipLan, $sMask)
    If @error Then Return SetError(@error, @extended, -1)
    Return $aLan[7][0]
EndFunc   ;==>_Make_Range

Func _GetLanParameters($theIP1, $sSubNet)
    ; ------------------------------------------
    ; calculate all IP/subnet related parameters
    ; ------------------------------------------
    If Not _isIPaddr($theIP1) Then Return SetError(3, 0, -1) ; wrong IP address
    ;check on subnet
    If Not _isSNmask($sSubNet) Then ; it is not a valid 4 digit subnet
        If $sSubNet > 0 And $sSubNet < 33 Then ; is it a CIDR notation number? nr. of bits 1 to 32
            $sSubNet = _CIDR_To_Mask($sSubNet)
        Else
            Return SetError(4, 0, -1) ; wrong Mask provided
        EndIf
    EndIf

    Local $aLan[8][5] ; net parameters container
    Local $sDot[2] = ['', '.'] ; used as IP octets separator
    Local $aIP = StringSplit($theIP1, '.'), $aSubNet = StringSplit($sSubNet, '.')
    ; split IP address in single octets and calculate related parameters
    For $i = 1 To 4
        $aLan[0][$i] = $aIP[$i] ;                           IP
        $aLan[1][$i] = $aSubNet[$i] ;                       NetMask
        $aLan[2][$i] = BitNOT($aLan[1][$i] - 256) ;         Wildcard, is the inverse of subnet: BitNot($NetMask - 256)
        $aLan[3][$i] = BitAND($aLan[0][$i], $aLan[1][$i]) ; LanAddress  BitAnd(IP, netmask)
        $aLan[4][$i] = BitOR($aLan[0][$i], $aLan[2][$i]) ;  Broadcast address
        $aLan[5][$i] = $aLan[3][$i] ;                       preset First host ; will be $NetAddress + 1
        $aLan[6][$i] = $aLan[4][$i] ;                       preset Last host  ; will be $Broadcast  -1
    Next
    If $sSubNet <> "255.255.255.255" Then
        $aLan[5][4] = BitOR($aLan[5][4], 1) ;                   First host $NetAddress + 1 (Turn last bit ON)
        $aLan[6][4] = BitAND($aLan[6][4], 254) ;                Last host $Broadcast  -1 (Turn last bit OFF)
    EndIf

    For $i = 1 To 4
        $aLan[0][0] &= $aLan[0][$i] & $sDot[$i < 4] ; [0] IP
        $aLan[1][0] &= $aLan[1][$i] & $sDot[$i < 4] ; [1] NetMask
        $aLan[2][0] &= $aLan[2][$i] & $sDot[$i < 4] ; [2] Wildcard
        $aLan[3][0] &= $aLan[3][$i] & $sDot[$i < 4] ; [3] Network
        $aLan[4][0] &= $aLan[4][$i] & $sDot[$i < 4] ; [4] Broadcast
        $aLan[5][0] &= $aLan[5][$i] & $sDot[$i < 4] ; [5] First host
        $aLan[6][0] &= $aLan[6][$i] & $sDot[$i < 4] ; [6] Last host
        ;                                             [7][0] Range for _nPing
        If $aLan[5][$i] = $aLan[6][$i] Then
            $aLan[7][0] &= $aLan[5][$i] & $sDot[$i < 4]
        Else
            $aLan[7][0] &= $aLan[5][$i] & "-" & $aLan[6][$i] & $sDot[$i < 4]
        EndIf
    Next
    ; MsgBox(0, "net", "IP address: " & @TAB & $aLan[0][0] & @CRLF & "Subnet:      " & @TAB & $aLan[1][0] & @CRLF & "Wildcard:   " & @TAB & $aLan[2][0] & @CRLF & "Network:   " & @TAB & $aLan[3][0] & @CRLF & "Broadcast: " & @TAB & $aLan[4][0] & @CRLF & "First host:   " & @TAB & $aLan[5][0] & @CRLF & "Last host:   " & @TAB & $aLan[6][0])
    ; _ArrayDisplay($aLan, "IP/subnet related parameters")
    Return $aLan
EndFunc   ;==>_GetLanParameters
; #FUNCTION# ====================================================================================================================
; Name...........: _LanParameters
; Description ...: given an IP and his subnet returns [and  displays] the following values in dec and binary format:
;                  |IP Address
;                  |Netmask
;                  |Wildcard
;                  |Network Address
;                  |Broadcast Address
;                  |First host
;                  |Last host
; Syntax.........: _LanParameters([$IP, $Subnet])
; Parameters ....:
;
; Return values .:
; Author ........:
; Modified.......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......:
; ===============================================================================================================================

Func _LanParameters($theIP1 = "", $sSubNet = "255.255.255.255", $Msg = 0)
    Static $TCP = TCPStartup()
    If $theIP1 = "" Then
        $theIP1 = TCPNameToIP(@ComputerName)
        ; $sSubNet = _GetSubnetMask($theIP1)
        $sSubNet = "255.255.255.0"
    ElseIf $sSubNet = "" Then
        $sSubNet = "255.255.255.255"
    EndIf
    If Not _isSNmask($sSubNet) Then ; it is not a 4 digit subnet
        If $sSubNet > 0 And $sSubNet < 33 Then ; is it a CIDR notation number? nr. of bits 1 to 32
            $sSubNet = _CIDR_To_Mask($sSubNet)
        Else
            Return SetError(4, 0, False) ; wrong mask
        EndIf
    EndIf

    Local $aLan = _GetLanParameters($theIP1, $sSubNet)
    Local $LanID[7][3]
    $LanID[0][0] = "IP Address       "
    $LanID[1][0] = "Netmask  "
    $LanID[2][0] = "Wildcard         "
    $LanID[3][0] = "Network Address  "
    $LanID[4][0] = "Broadcast Address"
    $LanID[5][0] = "First host       "
    $LanID[6][0] = "Last host        "
    For $i = 0 To 6
        $LanID[$i][1] = $aLan[$i][0]
        $LanID[$i][2] = _Convert_To_Binary($aLan[$i][1]) & "." & _Convert_To_Binary($aLan[$i][2]) & "." & _Convert_To_Binary($aLan[$i][3]) & "." & _Convert_To_Binary($aLan[$i][4])
    Next
    If $Msg Then MsgBox(0, "Lan IDs", $LanID[0][0] & @TAB & $LanID[0][2] & @TAB & $LanID[0][1] & @CRLF & _
            $LanID[1][0] & "( " & _Mask_To_CIDR($LanID[1][1]) & " ) " & @TAB & $LanID[1][2] & @TAB & $LanID[1][1] & @CRLF & _
            $LanID[2][0] & @TAB & $LanID[2][2] & @TAB & $LanID[2][1] & @CRLF & _
            $LanID[3][0] & @TAB & $LanID[3][2] & @TAB & $LanID[3][1] & @CRLF & _
            $LanID[4][0] & @TAB & $LanID[4][2] & @TAB & $LanID[4][1] & @CRLF & _
            $LanID[5][0] & @TAB & $LanID[5][2] & @TAB & $LanID[5][1] & @CRLF & _
            $LanID[6][0] & @TAB & $LanID[6][2] & @TAB & $LanID[6][1] & @CRLF)
    Return $LanID
EndFunc   ;==>_LanParameters

; #FUNCTION# ====================================================================================================================
; Name...........: _CIDR_To_Mask
; Description ...: transform a CIDR number (1 - 32) to the corresponding 4 digit mask
; Syntax.........: _CIDR_To_Mask($CIDR)
; Parameters ....: $CIDR a number from 1 to 32
; Return values .: a 4 bite corresponding subnet mask
; ===============================================================================================================================

Func _CIDR_To_Mask($sSubNet) ; From nr. of bit to 4 digit mask
    $sSubNet = StringLeft(StringLeft("11111111111111111111111111111111", $sSubNet) & "0000000000000000000000000000000", 32)
    $sSubNet = _Bin_To_Dec(StringLeft($sSubNet, 8)) & "." & _Bin_To_Dec(StringMid($sSubNet, 9, 8)) & "." & _Bin_To_Dec(StringMid($sSubNet, 17, 8)) & "." & _Bin_To_Dec(StringRight($sSubNet, 8))
    Return $sSubNet
EndFunc   ;==>_CIDR_To_Mask

; #FUNCTION# ====================================================================================================================
; Name...........: _Mask_To_CIDR
; Description ...: transform a 4 digit mask to the corresponding CIDR number (1 - 32)
; Syntax.........: _Mask_To_CIDR($SubnetMask)
; Parameters ....: $SubnetMask a 4 bite subnet mask
; Return values .: the corresponding CIDR
; ===============================================================================================================================

Func _Mask_To_CIDR($sSubNet) ; from 4 digit mask to nr. of bits
    If _isSNmask($sSubNet) Then
        Local $Digit = StringSplit($sSubNet, ".", 2)
        Return StringInStr(_Convert_To_Binary($Digit[0]) & _Convert_To_Binary($Digit[1]) & _Convert_To_Binary($Digit[2]) & _Convert_To_Binary($Digit[3]), "1", 0, -1)
    Else
        Return SetError(4, 0, False) ; wrong mask
    EndIf
EndFunc   ;==>_Mask_To_CIDR

Func _isIPaddr($sIPAddr) ; returns true if argument is a plausible IP address
    If Not StringRegExp($sIPAddr, "^((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d)$") Then Return SetError(1, 0, False)
    Return True
EndFunc   ;==>_isIPaddr

Func _isSNmask($sSNmask) ; returns true if argument is a correct 4 digit network mask
    If Not StringRegExp($sSNmask, "^(((255\.){3}(255|254|252|248|240|224|192|128|0+))|((255\.){2}(255|254|252|248|240|224|192|128|0+)\.0)|((255\.)(255|254|252|248|240|224|192|128|0+)(\.0+){2})|((255|254|252|248|240|224|192|128|0+)(\.0+){3}))$") Then Return SetError(1, 0, False)
    Return True
EndFunc   ;==>_isSNmask

Func _Convert_To_Binary($iNumber) ; from decimal to binary
    ; http://www.autoitscript.com/forum/topic/90056-decimal-to-binary-number-converter/?p=647505
    Local $sBinString = ""
    While $iNumber
        $sBinString = BitAND($iNumber, 1) & $sBinString
        $iNumber = BitShift($iNumber, 1)
    WEnd
    ; limit returned value to 8 bit 0 - 255
    Return StringRight("00000000" & $sBinString, 8)
EndFunc   ;==>_Convert_To_Binary

Func _Bin_To_Dec($BinNum) ; from binary to decimal
    Local $dec = 0
    For $i = 0 To StringLen($BinNum) - 1
        $dec += 2 ^ $i * StringMid($BinNum, StringLen($BinNum) - $i, 1)
    Next
    Return $dec
EndFunc   ;==>_Bin_To_Dec

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Link to comment
Share on other sites

I think I'm getting you now.  You want to feed in a pattern of an IP, say 190/2.13/52/7.0.12/62. 

Then generate an SRE for:

1st octet = 19 followed by one of 0,1,2 

2ND octet = 1 followed by one of 3,4,5 followed by one of 2,3,4,5,6,7

3RD octet = 0

4TH octet = 1 followed by one of 2,3,4,5,6 followed by 2.

Is that correct?

edit: This pattern doesn't make sense to me.

^64.237.(3[2-9]|[45][0-9]|6[0-3]).[0-9]+$

third octet = 3 followed by 2 thru 9 or 4 or 5 (4 or 5 is included in 2 thru 9)

                    followed by 0 thru 9 or 6 (again, 6 is included in previous range)

                    followed by 0 thru 3.

Maybe I'm misunderstanding what the pattern does...

Nevermind, I an not interpreting the pattern correctly...

Edited by kylomas

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Link to comment
Share on other sites

I think I'm getting you now.  You want to feed in a pattern of an IP, say 190/2.13/52/7.0.12/62. 

Then generate an SRE for:

1st octet = 19 followed by one of 0,1,2 

2ND octet = 1 followed by one of 3,4,5 followed by one of 2,3,4,5,6,7

3RD octet = 0

4TH octet = 1 followed by one of 2,3,4,5,6 followed by 2.

Is that correct?

lol I have no idea at all what you just typed.

Let me just say, ignore my end goals because for some reason it is confusing everyone. I want to generate a regular expression which encapsulates a number range. Lets say I want a regular expression to match between 0 and 9 I can do [0-9] To match numbers between 1 and 100 would be ([0-9]|[1-9][0-9]|100) I take these individual small pieces and build a full regular expression which starts with ^ includes each number regex pattern followed by . (because it is part of an IP address and ends with $.

Link to comment
Share on other sites

I think that the string returned by the _Make_Range() function in my post #14 could be easly transformed in an RegEx (by an regex expert)

edit:

it seems to me that the string returned by _Make_Range()  is what you need, only that it's not in regex format

Edited by Chimp

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Link to comment
Share on other sites

I think that the string returned by the _Make_Range() function in my post #14 could be easly transformed in an RegEx (by an regex expert)

edit:

it seems to me that the string returned by _Make_Range()  is what you need, only that it's not in regex format

I already have the range. I have everything broken down, two arrays containing octets for both the starting IP and ending IP. I am only wanting to generate regular expression patterns which will match a number in a range from 1 to 3 digits. Thats it. Once I have that I can build it into what I am wanting to do relating with IP's. All I need is that. Nothing else. 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...