Skip to content

Instantly share code, notes, and snippets.

@TheYarin
Created January 13, 2019 17:04
Show Gist options
  • Save TheYarin/e1a954c888d25172774987fe6fb73bc4 to your computer and use it in GitHub Desktop.
Save TheYarin/e1a954c888d25172774987fe6fb73bc4 to your computer and use it in GitHub Desktop.
A good IPv4 regex in C#. Should work for most languages with some tweaks.
const string ZERO_TO_255 = "(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
static readonly string IP_REGEX_PATTERN = $@"({ZERO_TO_255}\.){{3}}{ZERO_TO_255}";
static readonly Regex FindIPRegex = new Regex(IP_REGEX_PATTERN, RegexOptions.Compiled);
static readonly Regex ValidateIPRegex = new Regex($"^{IP_REGEX_PATTERN}$", RegexOptions.Compiled);
@TheYarin
Copy link
Author

In JS/TS:

const ZERO_TO_255 = "(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
const IP_REGEX_PATTERN = `(${ZERO_TO_255}\\.){3}${ZERO_TO_255}`;
const ValidateIPRegex = new RegExp(`^${IP_REGEX_PATTERN}$`);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment