Regular Expressions 101

Community Patterns

RegEx for Treating Express Route

1

Regular Expression
ECMAScript (JavaScript)

/
(\^)|(\\)(!?.+[a-zA-Z])(\\.*)
/
g

Description

A Regex that can be applied over the following routes pattern:

GET ^\/auth\/?(?=\/|$)/generate
GET ^\/auth\/?(?=\/|$)/callback

Applying it inside a code, it will get like this:

// Imprimir as rotas. Ref. https://stackoverflow.com/a/28199817/8297745
function printRoutes(stack, parentPath = '') {
    stack.forEach(middleware => {
        if (middleware.route) { // Caso seja uma rota
            const methods = Object.keys(middleware.route.methods).map(method => method.toUpperCase()).join(', ');
            console.log(`${methods} ${parentPath + middleware.route.path}`);
        } else if (middleware.name === 'router') {
            // Caso seja um sub-roteador (Ex: /auth)
            printRoutes(
                middleware.handle.stack,
                `${parentPath}${middleware.regexp.source.replace(
                    // Remover caracteres especiais da rota com regex. Ref. 
                    /(\^)|(\\)(!?.+[a-zA-Z])(\\.*)/g, '$3'
                )}`);
        }
    });
}
Submitted by HorselessName - 5 months ago