I want to generate regex strings to match IP-addresses in a given CIDR range.
Yes. I know this is stupid. Yes I know regex isn't ideal for handling IP-addresses. I'm just trying to work with what I've got. And to get all the eventual x/y-problem sorts of comments out of the way:
The place where I need to *use *these regexes does not support straight up IP-ranges, nor CIDR notation "natively" all I can work with is regex operating on strings. So I can't just use the "Contains" method from a [System.Net.IPNetwork] object, for example.
So given for example an input of 10.10.10.0/24, I would want function that outputs ^10\.10\.10\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)$
and for a larger network such as a 123.123.120.0/20 a resulting regex would be something like ^123\.123\.(12[0-7])\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)$
I've found various LLM tools to be fairly proficient at generating these for specific examples, but I'm getting stuck on writing a general purpose function to do it for any given (valid) CIDR input.
I "only" need it to work on IPv4 addresses, IPv6 is not relevant for my use case.
The intended use is to programmatically generate/convert these strings from arbitrary input, but more specifically the IP ranges published by Microsoft for various M365 services (https://learn.microsoft.com/en-us/microsoft-365/enterprise/microsoft-365-ip-web-service?view=o365-worldwide) which are published as for example just 52.100.0.0/14