Usar regex capturing y non-capturing groups
Groups (...) capture submatches para backreferences y extraction. Non-capturing (?:...) group sin capturing. Named groups (?<name>...) improve readability.
- 1
Parentheses create groups. Capturing groups (...) save the matched substring for later use (backreferences, replacement, extraction). Non-capturing (?:...) group for alternation or repetition without saving. Named groups (?<name>...) or (?P<name>...) assign a name for readability. Groups are numbered left-to-right by opening parenthesis.
- 2 Probador de regex →
Test patterns with groups. Use (\d{4})-(\d{2})-(\d{2}) to extract year, month, day from a date. The tool shows captured groups by number. Use named groups (?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2}) for clarity.
- 3 Reemplazo con regex →
Use captured groups in replacements. Replace (\d{4})-(\d{2})-(\d{2}) with $2/$3/$1 to reorder a date from YYYY-MM-DD to MM/DD/YYYY. In JavaScript, use $1, $2 for numbered groups or $<name> for named groups.
Preguntas frecuentes
- What is the difference between (...) and (?:...)?
- (...) is a capturing group — it saves the matched text for later use ($1, \1) but uses memory and slightly slows matching. (?:...) is non-capturing — it groups for alternation or repetition without saving. Use non-capturing when you don't need the captured value, for performance and clarity.
- How do named groups work?
- (?<name>pattern) creates a named capturing group. In JavaScript (ES2018+), access via match.groups.name. In replacement, use $<name>. Named groups are also numbered (left-to-right), so $1 still works. They improve readability in complex patterns.