Use regex quantifiers: *, +, ?, {n,m}
Quantifiers 指定如何许多 times 模式 repeats. Learn greedy, lazy, 和 possessive matching 到 avoid catastrophic backtracking.
- 1
Quantifiers: * (0 或更多), + (1 或更多), ? (0 或 1), {n} (exactly n), {n,m} (n 到 m), {n,} (n 或更多). 通过默认它们是 greedy (匹配 as much as 可能). Add ? 为 lazy (匹配 as 小 as 可能): *?, +?, ??. Add + 为 possessive (否 backtracking): *+, ++. Lazy 是常见; possessive prevents catastrophic backtracking.
- 2 正则表达式测试器 →
Test greedy vs lazy quantifiers. Compare。* (greedy, matches 到结束) vs。*? (lazy, matches 最小值). 为 HTML like <div>内容</div>, <.*> matches 整个字符串 (greedy), while <.*?> matches <div> 仅 (lazy).
- 3 正则表达式替换器 →
Use quantifiers 在 replacements. 替换 \d{4} 具有 **** 到 mask 4-数字 numbers, 或 [a-z]+ 到替换 words. Test 具有 various 输入到 验证 quantifier matches intended 数字的 repetitions.
常见问题
- 什么是 catastrophic backtracking?
- 当 regex 具有 nested quantifiers (e.g., (+)+) fails 到匹配, engine tries exponentially 许多 combinations 之前 giving 上. 此能够 hang 为 minutes 开短 输入. Fix 具有 possessive quantifiers (++)+, atomic groups, 或 rewrite 模式. 总是集合超时为 regex 开 untrusted 输入.
- 当到 use lazy vs greedy?
- Use lazy (*?, +?) 当你 want shortest 匹配, 通常当 matching 之间 delimiters (HTML tags, quoted strings). Use greedy (*, +) 当你 want longest 匹配, 通常当 matching 到结束的 行或 当模式是 anchored. 最多实数-world cases use lazy 为 delimited 内容.