gpt4 book ai didi

javascript - 正则表达式捕获多行模式

转载 作者:行者123 更新时间:2023-11-28 05:01:23 26 4
gpt4 key购买 nike

我无法捕捉多行中的重复模式。我相信这是一项简单的任务,但我似乎无法让它发挥作用!

Check this example : (.*\s*) 的用户

Users of 85838NAVSIM_F:  (Total of 2 licenses issued;  Total of 2 licenses in use)

----- ends here!

"85838NAVSIM_F" v1.000, vendor: adskflex
floating license

1 RESERVATION for PROJECT 1 (SRV02/27000)

----- should catch to here (and repeat on next)!

Users of 67600NAVMAN_F: (Total of 2 licenses issued; Total of 2 licenses in use)

"67600NAVMAN_F" v1.000, vendor: adskflex
floating license

1 RESERVATION for PROJECT 2 (SRV02/27000)

为什么仅仅.*(任何字符,包括换行符?多次)不足以捕获多行?如何调整正则表达式以使其按预期工作?

谢谢!!

最佳答案

我建议使用调和的贪婪 token 并依赖 [^][\s\S]匹配任何字符,因为在 JS 正则表达式中,由于缺少 DOTALL/s ,无法重新定义点行为修饰符。

使用

/^Users of (?:(?!^Users of )[\s\S])*/gim

请参阅regex demo

详细信息

  • ^ - 行的开头(使用 m 修饰符时,^ 匹配字符串和行的开头)
  • Users of - 文字字符序列
  • (?:(?!^Users of )[\s\S])* - 与任何字符(请参阅 [\s\S] = [^] )匹配零次或多次(请参阅 * )的调和贪婪 token 不启动 Users of行首的子字符串

相同的展开正则表达式看起来像

/^Users of .*(?:\r?\n(?!Users of ).*)*/gim

参见another regex demo .

这里,经过调和的贪婪 token 展开为

  • .* - Users of 之后的其余行
  • (?:\r?\n(?!Users of ).*)* - 零次或多次出现:
    • \r?\n - 换行符(可以替换为 (?:\r\n?|\n) 以匹配任何常见样式的换行符)...
    • (?!Users of ) - 后面没有 Users of子串
    • .* - 该行的其余部分。

关于javascript - 正则表达式捕获多行模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42110588/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com