DEV Community

Discussion on: How do you regex?

Collapse
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan

I like using regexr.com/ to test my regex and make sure it behaves correctly for edge cases. It's a wonderful tool!

These days, I mainly use regex at the editor level (e.g., in VS Code) to mass-replace certain patterns with other patterns when it's not possible to easily rename them using built-in editor shortcuts. For example, in early 2021, I migrated my site from Jekyll to 11ty, and as part of that migration, I had to convert a bunch of my Liquid shortcodes to use a new syntax. Since I had hundreds of matches, I relied on regex to mass-replace them rather than doing it by hand.

More recently, I also learned about the HTML pattern attribute, which accepts any valid regex to validate a form input, and have been using it where appropriate for client-side validation. For example, in a recent project, I used the pattern ^[a-zA-Z0-9-](?:(,\s*)?[a-zA-Z0-9-])*$ to match a comma-separated list of identifiers, with potential spaces after the commas. It seemed difficult to arrive at this solution initially, but then I realized that it was just a more complex case of the slug regex pattern I used here: npmjs.com/package/is-slug.

While I find it easy to compose basic regex patterns, I do think it's harder to read regex, especially for complex patterns like the one above, and especially if I'm reading other people's regex.