为什么正则表达式补集字符类(^)无法捕获全部匹配结果?
问题原因
你写的正则出错的核心原因是[^(Æ¢)]的用法错误:方括号[]内的字符集只会匹配单个字符,你写的[^(Æ¢)]实际含义是「匹配所有不等于(、Æ、¢、)的单个字符」,而第二个示例的内容里包含括号(,匹配到括号时就直接中断了,所以只能拿到第一个结果。
修复方案
要实现匹配{Æ¢到Æ¢}之间的所有内容,改用惰性匹配逻辑即可,正则修改如下:
// 加s标志让.可以匹配换行符,适配内容中存在换行的场景 const regex = /{Æ¢\s*(.*?)\s*Æ¢}/gs;
如果需要直接提取去了前后空格的大括号内的内容,可以用matchAll遍历结果提取分组内容:
let str = `First example (working): {Æ¢ Example phrase 123 áè -*, example Æ¢} Second example (not working): {Æ¢ A SuperSlim notebook computer that's light on weight, heavy on features and performance *This .9 thin Notebook Computer weighs in at roughly 3 pounds - which might make you wonder how they cram such great features into that small package *10.4 XGA Active matrix screen with XBRITE display technology *Intel Pentium 300 MHz processor with MMX technology *64 MB of SDRAM is included (expandable to 128 MB maximum) *6.4 GB fixed Hard Drive for Data Storage *Touch Pad with pen operation *One Type II PC card slot with Cardbus Zoomed Video support *External 1.44 MB floppy disk drive *integrated 56K V.90 Data/fax Modem for Internet access *512 KB MultiBank DRAM Cache memory *16-bit, Soundblaster compatible audio *MPEG1 Digital video that supports full screen playback *mono speakers *Built-in microphone *Infrared port *Responsive nearly full-size tactile Keyboard *programmable power key for unattended Email retrieval Please add $30 for shipping. Payment - western union. Æ¢}` const result = [...str.matchAll(/{Æ¢\s*(.*?)\s*Æ¢}/gs)].map(item => item[1]); console.log(result);
运行后会输出两个你需要的内容:
[ 'Example phrase 123 áè -*, example', "A SuperSlim notebook computer that's light on weight, heavy on features and performance *This .9 thin Notebook Computer weighs in at roughly 3 pounds - which might make you wonder how they cram such great features into that small package *10.4 XGA Active matrix screen with XBRITE display technology *Intel Pentium 300 MHz processor with MMX technology *64 MB of SDRAM is included (expandable to 128 MB maximum) *6.4 GB fixed Hard Drive for Data Storage *Touch Pad with pen operation *One Type II PC card slot with Cardbus Zoomed Video support *External 1.44 MB floppy disk drive *integrated 56K V.90 Data/fax Modem for Internet access *512 KB MultiBank DRAM Cache memory *16-bit, Soundblaster compatible audio *MPEG1 Digital video that supports full screen playback *mono speakers *Built-in microphone *Infrared port *Responsive nearly full-size tactile Keyboard *programmable power key for unattended Email retrieval Please add $30 for shipping. Payment - western union." ]
如果需要保留外层的大括号和首尾的Æ¢,直接用修改后的正则调用match即可:
console.log(str.match(/{Æ¢\s*.*?\s*Æ¢}/gs));
内容的提问来源于stack exchange,提问作者FCLM
相关产品推荐
相关产品推荐

