DEV Community

Discussion on: Regex Cheat Sheet

Collapse
 
dystroy profile image
Denys Séguret • Edited

Making code readable is half the job of the coder. It's also true for regexes, which means you have to look for ways to separate parts and comment your regexes (or at least name the groups).

Fortunately, you can find solutions in most languages. Here are two examples from some of my OS codes:

In Javascript:

    cmdArgRegex = miaou.lib("rex")`
            ([a-z ]*)                        // options (optional)
            (-?\d*\s*d\s*[\d+-]+)            // left rolldef (mandatory)
            (?:                              // inequation (optional)
                    \s*
                    ([<>=]+)                 // operator
                    \s*
                    ([\w+-]+)                // right rolldef or scalar
            )?
            \s*$
            /i`;

(I think there are JS libs to do that without taking my code, now)

In rust:

        static ref RE: Regex = Regex::new(
            r"(?x)
            ^
            (?P<slash_before>/)?
            (?P<pattern>[^\s/:]+)?
            (?:/(?P<regex_flags>\w*))?
            (?:[\s:]+(?P<verb>\S*))?
            $
            "

(this is the standard way in this language)