Use regex capturing 和 non-capturing groups
Groups (...) capture submatches 为 backreferences 和 extraction. Non-capturing (?:...) 组无 capturing. Named groups (?<name>...) improve readability.
- 1
Parentheses 创建 groups. Capturing groups (...) 保存 matched substring 为稍后 use (backreferences, replacement, extraction). Non-capturing (?:...) 组为 alternation 或 repetition 无 saving. Named groups (?<name>...) 或 (?P<name>...) 分配 name 为 readability. Groups 是 numbered left-to-right 通过打开 parenthesis.
- 2 正则表达式测试器 →
Test patterns 具有 groups. Use (\d{4})-(\d{2})-(\d{2}) 到提取 year, month, day 从日期. tool shows captured groups 通过数字. Use named groups (?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2}) 为 clarity.
- 3 正则表达式替换器 →
Use captured groups 在 replacements. 替换 (\d{4})-(\d{2})-(\d{2}) 具有 $2/$3/$1 到 reorder 日期从 YYYY-MM-DD 到 MM/DD/YYYY. 在 JavaScript, use $1, $2 为 numbered groups 或 $<name> 为 named groups.
常见问题
- 什么是 差集之间 (...) 和 (?:...)?
- (...) 是 capturing 组 — 它 saves matched 文本为 稍后 use ($1, \1) 但我们内存和 slightly 慢 matching. (?:...) 是 non-capturing — 它 groups 为 alternation 或 repetition 无 saving. Use non-capturing 当你 don't need captured 值, 为性能和 clarity.
- 如何 named groups 工作?
- (?<name>模式) creates named capturing 组. 在 JavaScript (ES2018+), access via 匹配.groups.name. 在 replacement, use $<name>. Named groups 是 also numbered (left-to-right), 所以 $1 仍然工作. 它们 improve readability 在复杂 patterns.