Skip to content

Instantly share code, notes, and snippets.

@msanders
Last active January 26, 2024 00:18
Show Gist options
  • Save msanders/f88861073aeeae7ade1cc60728331d44 to your computer and use it in GitHub Desktop.
Save msanders/f88861073aeeae7ade1cc60728331d44 to your computer and use it in GitHub Desktop.
Verbose regular expressions and memoization in fish shell

Implementation

Converts a verbose regex back to compact form, i.e. joined and without comments or unescaped whitespace. Similar to re.VERBOSE in Python.

function verbose_regex --argument-names pattern --description "Converts a \
verbose regex back to compact form, i.e. joined and without comments or \
unescaped whitespace. Similar to re.VERBOSE in Python"
    # See https://docs.python.org/2/library/re.html#re.VERBOSE
    echo $pattern |
        string replace --regex '#.*$' "" |
        string replace --all --regex '(^|[^\\\\])\s+' '$1' |
        string replace --all --regex '\\\\(\s)' '$1' |
        string match --entire --regex . |
        string join ""
end

Example

set x (verbose_regex "
    \p{L}+  # prefix
    [ _ - ] # delimiter
    \p{L}+  # suffix
")
echo $x # \p{L}+[_-]\p{L}+
string match --regex $x "verbose_regex123" # verbose_regex

Memoization

Can cache output to improve performance:

set __memoize_keys
set __memoize_values
function __memoize_underlying_fn --argument-names funcname
    echo '__memoize_'$funcname
end

function memoize --argument-names funcname
    functions --copy $funcname (__memoize_underlying_fn $funcname)
    function $funcname
        # See https://stackoverflow.com/a/40019138/12638282
        set --local fn (__memoize_underlying_fn (status function))
        set --local key $fn'/'$argv # / is an invalid function character in fish
        if set --local index (contains -i -- $key $__memoize_keys)
            echo $__memoize_values[$index]
        else
            set --local value ($fn $argv)
            set --append __memoize_keys $key
            set --append __memoize_values $value
            echo $value
        end
    end
end

memoize verbose_regex

License

This is made available under the terms of the MIT license. For a copy, see https://opensource.org/licenses/MIT.

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