Home > other >  Match url path and ip address from string
Match url path and ip address from string

Time:10-04

How to match two parts of the string?

Example string:

/some/page_path 255.122.212.211

The first part I want to match is a valid path, a simple check if starts with / and no white spaces. (and maybe special signs?)

The second part is just checking the IP address if has a pattern of (0-9) numbers with dots.

Example of bad string:

/some/page _path 2525.122.212 yada yada

Regex I have for IP:

^(?:[0-9]{1,3}\.){3}[0-9]{1,3}

CodePudding user response:

You can use

/\A(?:\/[^\/\s] ) \s (?:[0-9]{1,3}\.){3}[0-9]{1,3}\z/

See the Rubular demo. Details:

  • \A - start of string
  • (?:\/[^\/\s] ) - one or more occurrences of / and then one or more chars other than / and whitespace
  • \s - one or more whitespace chars
  • (?:[0-9]{1,3}\.){3}[0-9]{1,3} - three occurrences of one to three digits followed with a . char, and then one to three digits
  • \z - end of string.
  • Related