首页 > 解决方案 > 为什么我的正则表达式没有得到补充字符类 (^) 中的所有匹配项?

问题描述

有人可以启发我,我尝试了很多东西,但这不起作用。我将给出我收到错误的示例:

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. Ƣ}`

// Regex
console.log(
   str.match(/{Æ¢\s*([^(Æ¢)]*)\s*Æ¢}/g));

我正在修剪空格并将所有内容都放在大括号内,然后是“Æ¢”,直到“Æ¢}”结果只是字符串中的第一个示例,它不包括第二个:

> ["{Æ¢ Example phrase 123 áè -*, example Æ¢}"]

标签: javascriptregex

解决方案


例如:

const 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\n 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 allMatches = str.matchAll(/{Æ¢\s*(.*?)\s*Æ¢}/gs);

for (let match of allMatches) {
  console.log(match[1]);
}

s标志中的开启gs“单行”或“dotAll”模式,以便.匹配换行符。

意思是“懒惰地”匹配,即在?匹配模式的其余部分之前匹配尽可能少的字符。

全局匹配并使用捕获组时,matchAllexec必须使用。


推荐阅读