Afsheen Taheri
Afsheen Taheri

Reputation: 139

Need expression not to match after a colon appear

So I have a list of names and wanted to filter out the ones in proper format. For reference, the format I need is IP::hostname. This is the regex formula I currently have:

^\d+(\.|\:)\d+\.\d+\.\d+::.+\w$

However, I need to modify it so that if there are any colons (:) in or after the hostname, for it to not match the expression:

This matches which is correct:

10.179.12.241::CALMGTVCSRM0210

This matches but should not:

10.179.12.241::CALMGTVCSRM0210:as

Any help on how to modify my expression to not match any colons after the host name would be appreciated

Upvotes: 2

Views: 68

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627103

The .+ pattern matches 1 or more chars other than line break chars, as many as possible, and thus matches colons allowing them. You need a negated character class, [^:]*, that will match 0+ chars other than a colon.

You may fix you regex (and enhance a bit) using

^\d+[.:]\d+\.\d+\.\d+::[^:]*\w$
                       ^^^^^

See the regex demo

To make sure you want to match a valid IP you'd rather use

^(?: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]?)){3}::[^:]*\w$

See another regex demo (IP regex source). The (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) matches a single octet from 0 to 255 and (?:\.<octet_pattern>){3} matches three repetitions of a dot and an octet pattern.

Upvotes: 1

Related Questions