Skip to content
Advertisement

How to match IP addresses in a comma-separated string

Code show as below, but there is a problem: “255.255.255.256” will be processed into “255.255.255.25”

JavaScript

If I pass the 255.255.255.255,255.255.255.256,260.255.255.255 string I expect ["255.255.255.255"] as the results.

Advertisement

Answer

You want to implement comma boundaries, (?<![^,]) and (?![^,]):

JavaScript

See the regex demo.

Details

  • (?<![^,]) – a negative lookbehind that matches a location not immediately preceded with a char other than a comma (i.e. there must be a comma or start of string immediately to the left of the current location)
  • (?![^,]) – a negative lookahead that matches a location not immediately followed with a char other than a comma (i.e. there must be a comma or end of string immediately to the right of the current location).

See the Python demo:

JavaScript
Advertisement