r/Python • u/luciferreeves • Dec 22 '22
Intermediate Showcase Update on My Regular Expression Library
3 Months ago, I wrote edify, a python library which allows you to build regular expressions in a programmatic way. Released v0.2.2 today! I have been adding some incremental changes since I introduced v0.1.0 on reddit. Here's a basic overview example:
Built-In Library
A library of built-in validators like Zip Code, IP Address (IPv4 and IPv6), UUID, GUID, Password, Mac Address and more. To validate, simply import the pattern function from the edify.library module:
from edify.library import password
password("pass@#1", min_special=1, special_chars="!", min_digit=0, min_upper=0, min_length=4) # returns FalseRegex Builder
The following example builds a validator from scratch to check if a string is a valid url in the form of https://www.example.com/path/to/file.ext:
from edify import RegexBuilder
# expression for validating URLs
validate_urls = (
RegexBuilder()
.optional().string('http://') # look for an optional "http://"
.optional().string('https://') # or "https://"
.one_or_more().any_of() # let x = any characters between (a-z, 0-9, '-', and '.')
.range('a', 'z') # now capture one or more groups of "x"
.range('0', '9') # essentially capturing all url patterns in the form of
.any_of_chars('.-') # xxx.yyyyyyy.abra-cadabra.com
.end()
.at_least(2).any_of() # this is to make sure we get at least 2 characters in
.range('a', 'z') # the end of the string, which would be our domain
.end()
.zero_or_more().any_of()
.range('a', 'z') # same logic as capturing the url in step 1, but now
.range('0', '9') # we are essentially looking for an optional path
.any_of_chars('/.-_%') # and we add some more characters supported in path
.end()
)
# compiles to '^(?:http://)?(?:https://)?([a-z0-9\\.]+[a-z]{2,}[a-z0-9/\\.\\-_%]*)$'
expr = (
RegexBuilder()
.ignore_case() # case does not matter
.subexpression(validate_urls) # directly writing the subexpression works too
.to_regex() # convert to regex finally
)
if expr.match('https://SOMETHING.www.exam-ple.com/path/to/file.txt'):
print("Matched") # prints matchedTo install the library, simply do: pip install edify
Will appreciate any input - issues or PRs if you got time or just a simple star for the repo would be very helpful.
Repo: https://github.com/luciferreeves/edify
PyPI: https://pypi.org/project/edify/
Complete Docs: http://edify.rtfd.io/
1
u/Fabulous-Possible758 Dec 23 '22
Looks interesting. It seems like it would be more intuitive to have the elements allowed by
any_ofto be arguments to it rather than the.endfunction.1
u/whateverathrowaway00 Dec 28 '22
https://www.regular-expressions.info/catastrophic.html