0

I have a regex that finds an ip:

'[0-9]+(?:\.[0-9]+){3}'

And now I need to make an Ip fail if it starts or ends with a dot. For example, these will fail:

- .1.1.1.1
- 1.1.1.1.
- 1.1.1.1.1
- 1.11.1.1.1
Golan Kiviti
  • 3,895
  • 7
  • 38
  • 63
  • Just use `^` and `$` anchors as shown [HERE](https://regex101.com/r/UJ3SzB/1) – Gurmanjot Singh Jun 03 '18 at 06:41
  • does the input actually contain dashes and whitespaces `- .1.1.1.1` ? Show your current code: what is the input and how do you find IPs in it? – RomanPerekhrest Jun 03 '18 at 06:43
  • @Gurman I need to find the ip inside a large text, your example doesnt work – Golan Kiviti Jun 03 '18 at 06:44
  • You may want to use a more sophisticated regex to match IPv4, e.g. https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address/106223#106223 – wp78de Jun 03 '18 at 06:44

1 Answers1

1

Try this regex:

(?<!\.)(?:[0-9]+(?:\.[0-9]+){3})(?!\.)

Click for Demo

Explanation:

  • (?<!\.) - Negative lookbehind to make sure that your IP pattern is not preceded by a .

  • (?:[0-9]+(?:\.[0-9]+){3}) - same as your pattern

  • (?!\.) - Negative lookahead to make sure that your IP pattern is not followed by a .

Also, Note that, the IP pattern can also be improved, if required.

Update

As per your comment, here is the updated regex(I have just added word boundaries so as to cover the case provided by you):

(?<!\.)\b\d+(?:\.\d+){3}\b(?!\.)

Gurmanjot Singh
  • 10,224
  • 2
  • 19
  • 43
  • Its almost what im looking for, expect, the following will also be found: - 1.11.1.1.1, ill get 1.1.1.1, and I dont want it – Golan Kiviti Jun 03 '18 at 06:55