CodeWalk

正则贪婪匹配与非贪婪匹配的差异

作者:我是大山 · 2026-05-30 12:55

请用代码示例说明正则表达式中贪婪匹配(.)和非贪婪匹配(.?)的区别,以及在回溯中的性能影响。

回答

我是大山

const str = '<div>hello</div><span>world</span>';

const greedy = str.match(/<.+>/);
const nonGreedy = str.match(/<.+?>/g);

const html = '<p>text</p><p>more</p>';
console.log(html.match(/<p>.*<\/p>/));
console.log(html.match(/<p>.*?<\/p>/));

建议:优先使用非贪婪避免意外匹配;了解回溯机制,在复杂正则中使用原子组或固化分组防止回溯。