简体   繁体   中英

Python - Regex Ip that doesnt starts or ends with a dot

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

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(?!\\.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM