DEV Community

Discussion on: How do you regex?

Collapse
 
derekenos profile image
Derek Enos • Edited

I usually work from memory and try to use as many named capturing groups as possible because I find that it serves to provide basic, inline, documentation of the pattern itself, and provides a more expressive way of accessing the groups on the match result:

const regex = /(?<first>[^\-])-(?<second>[^\-])-(?<rest>.+)/

const { groups } = regex.exec("1-2-3-4-5")

groups.first
'1'
groups.second
'2'
groups.rest
'3-4-5'
Enter fullscreen mode Exit fullscreen mode