Regular Expression Question

Hi RegEx gurus :slight_smile:

I have been trying to create a match pattern for only the third octet of an IP address. Where I get in trouble is that this third octet can be 1, 2, or 3 digits deep.
ie. 100.200.120.2 or 100.200.1.42

I need to match .120. on the first example and .1. on the second example.

All of my attempts get stuck on the second octet since the format is the same essentially as the third octet.

I am using RegExRx, but I think its more advanced than I :slight_smile:

Thank again everyone!

In the free samples that you can download through RegExRX, look at β€œFind IPv4 Address (subroutine)”. You can use that and find your answer within SubExpressionString( 4 ). Here is the pattern:

(?(DEFINE)(?'seg'25[0-5]|2[0-4]\\d|[01]?\\d{1,2}))\\b(?'seg1'(?&seg))\\.(?'seg2'(?&seg))\\.(?'seg3'(?&seg))\\.(?'seg4'(?&seg))\\b

I just realized that the sample left off the trailing β€œ\b” as shown above. If you re-download, you’ll have the most updated versions of all the sample, including that one.

Ah that is what I was missing also! I always had been using SubExpressionString(0)…

Thanks Kem!

[quote=35342:@Mike C]Hi RegEx gurus :slight_smile:

I have been trying to create a match pattern for only the third octet of an IP address. Where I get in trouble is that this third octet can be 1, 2, or 3 digits deep.
ie. 100.200.120.2 or 100.200.1.42

I need to match .120. on the first example and .1. on the second example.

All of my attempts get stuck on the second octet since the format is the same essentially as the third octet.

I am using RegExRx, but I think its more advanced than I :slight_smile:

Thank again everyone![/quote]
You could also use NthField

I ended up using Nthfield first and then regex second.

  // IPv4 Address Validation for 2nd Octet
  Dim FindTheString as String = NthField(Octet,".",3)
  
  ValidateThirdOctet_RegEx = New RegEx
  ValidateThirdOctet_RegEx.options.caseSensitive = true
  ValidateThirdOctet_RegEx.options.Greedy = True
  ValidateThirdOctet_RegEx.options.TreatTargetAsOneLine = false
  ValidateThirdOctet_RegEx.options.CaseSensitive = False
  
  // Valid IPv4 2nd Octet Range 0-255
  ValidateThirdOctet_RegEx.SearchPattern = "\\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-5][0-5])\\b"
  
  
  // Set the Regular Expression Target
  ValidateThirdOctet_RegExMatch = ValidateThirdOctet_RegEx.Search(FindTheString)
  
  
  if ValidateThirdOctet_RegExMatch <> nil then
    ValidateThirdOctet_RegEx_HitText = ValidateThirdOctet_RegExMatch.SubExpressionString(0)
    Return True
  elseif ValidateThirdOctet_RegExMatch  = nil then
    return False
  end if

Kem I just downloaded your Samples for RegExRx and they are perfect thank you. For others reading this as a reference here is the link to the RegExRx sample files.

RegExRx Sample Files

Good timing as I just (finally) organized them. :slight_smile: