gpt4 book ai didi

PHP - preg_match_all - 有点高级

转载 作者:可可西里 更新时间:2023-11-01 13:27:52 24 4
gpt4 key购买 nike

我需要在字符串中找到特定的文本部分。该文本需要:

  • 12 个字符(仅限字母和数字)
  • 整个字符串必须至少包含 3 位数字
  • 3*4 个带空格的字符(例如 K9X6 6GM6 LM11 )
  • 上述示例中的每个 block 必须至少包含 1 个数字
  • this这样的词, line , spod不应该被认可

enter image description here

所以我以这段代码结束:

preg_match_all("/(?<!\S)(?i:[a-z\d]{4}|[a-z\d]{12})(?!\S)/", $input_lines, $output_array);但它不适用于所有要求。我当然可以用preg_repacestr_replace并删除所有 (!,?,#) 并在循环中计数数字(如果有 4 个或更多)但我想知道是否可以使用 preg_match_all ...

这里是要搜索的字符串:

?K9X6 6GM6 LM11  // not recognized - but it should be
!K9X6 6GM6 LM11 // not recognized - but it should be
K0X6 0GM7 LM12! // not recognized - but it should be
K1X6 1GM8 LM13@ // not recognized - but it should be
K2X6 2GM9 LM14? // not recognized - but it should be
K3X6 3GM0 LM15# // not recognized - but it should be
K4X6 4GM1 LM16* // not recognized - but it should be
K5X65GM2LM17
bla bla bla
this shouldn't be visible
spod also shouldn't be visible
but line below should be!!
K9X66GM6LM11! (see that "!" at the end? Help me with this)

正确 preg_match_all应该返回这个:

K9X6
6GM6
LM11
K9X6
6GM6
LM11
K0X6
0GM7
LM12
K1X6
1GM8
LM13
K2X6
2GM9
LM14
K3X6
3GM0
LM15
K4X6
4GM1
LM16
K5X65GM2LM17
K9X66GM6LM11

工作示例:http://www.phpliveregex.com/p/bHX

最佳答案

以下应该可以解决问题:

\b(?:(?=.{0,3}?\d)[A-Za-z\d]{4}\s??){3}\b

Demo

  • [A-Za-z\d]{4} 匹配 4 个字母/数字
  • (?=.{0,3}?\d) 检查这 4 个字符中是否有数字
  • \s?? 匹配空白字符,但尽可能不匹配它
  • \b 确保所有内容都不包含在更大的词中

请注意,这将允许像 K2X6 2GM9LM14 这样的字符串,我不确定您是否希望这些匹配。

关于PHP - preg_match_all - 有点高级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31087353/

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