gpt4 book ai didi

PHP preg_grep 反向匹配模式

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:38:05 25 4
gpt4 key购买 nike

我构建了一个简单的代码来解析几个磁盘中的所有音乐文件夹并将列表放入一个数组中。

当文件夹名称是类别时,文件夹名称以多个空格开头,当它们是“最终文件夹”时,文件夹名称以单个空格开头。例如。看到这个结构:

[0] => /Volumes/SAMPLES/  VOCALS/
[1] => /Volumes/SAMPLES/ VOCALS/ AFRICA/
[2] => /Volumes/SAMPLES/ VOCALS/ AcmeInc Club Vocals/
[3] => /Volumes/SAMPLES/ VOCALS/ AtomicInc Dance Vocals/
[4] => /Volumes/SAMPLES/ VOCALS/ AFRICA/ AfroInc Zulu Vocals/
[5] => /Volumes/SAMPLES/ VOCALS/ AFRICA/ SampleInc Warriors/
[6] => /Volumes/SAMPLES/ VOCALS/ AFRICA/ SampleInc Warriors/SampleInc_Warriors_Ululation/
[7] => /Volumes/SAMPLES/ VOCALS/ AFRICA/ SampleInc Warriors/SampleInc_Warriors_Drums/

等等...我只需要选择最后的文件夹,并尝试了几种贪婪和非贪婪模式的组合,从最后的 $ 开始例如。以下路径不起作用:

$pattern = "#\/ ([:alnum:]+?)/$#i";
$matches = preg_grep ($pattern, $root);

预期的结果应该是:

[3] => /Volumes/SAMPLES/  VOCALS/ AcmeInc Club Vocals/
[4] => /Volumes/SAMPLES/ VOCALS/ AtomicInc Dance Vocals/
[5] => /Volumes/SAMPLES/ VOCALS/ AFRICA/ AfroInc Zulu Vocals/
[6] => /Volumes/SAMPLES/ VOCALS/ AFRICA/ SampleInc Warriors/

相反,我得到了所有文件夹或没有文件夹或孤立文件夹。请考虑像 &or 这样的特殊字符!可能在文件夹名称中。感谢您的建议,3天,尝试了一切,绝望,谢谢!

最佳答案

这是一个有效的正则表达式:

'~/(?:  +[^/\s]+)*/ [^/\s]+(?: +[^/\s]+)*/$~'

参见 regex demo

它匹配:

  • /(?: +[^/\s]+)* - 非最终子文件夹(/,然后多于1个空格,1个或多个字符除了空格或 /)
  • / - 正斜杠后面有一个空格
  • [^/\s]+ - 除了空格或正斜杠之外的 1 个或多个字符
  • (?: +[^/\s]+)* - 0 个或多个 ...
    • + - 1个或多个常规空格
    • [^/\s]+ - 除了空格或正斜杠之外的 1 个或多个字符
  • / - 正斜杠
  • $ - 字符串结尾

参见 PHP code demo :

$ar = array("/Volumes/SAMPLES/  VOCALS/", 
"/Volumes/SAMPLES/ VOCALS/ AFRICA/",
"/Volumes/SAMPLES/ VOCALS/ AcmeInc Club Vocals/",
"/Volumes/SAMPLES/ VOCALS/ AtomicInc Dance Vocals/",
"/Volumes/SAMPLES/ VOCALS/ AFRICA/ AfroInc Zulu Vocals/",
"/Volumes/SAMPLES/ VOCALS/ AFRICA/ SampleInc Warriors/",
"/Volumes/SAMPLES/ VOCALS/ AFRICA/ SampleInc Warriors/SampleInc_Warriors_Ululation/",
"/Volumes/SAMPLES/ VOCALS/ AFRICA/ SampleInc Warriors/SampleInc_Warriors_Drums/",
"/Volumes/SAMPLES/ VOCALS/ AFRICA/ AfroInc Zulu Vocals/ Folder1/"
);
$n = preg_grep('~/(?: +[^/\s]+)*/ [^/\s]+(?: +[^/\s]+)*/$~', $ar);
print_r($n);

结果:

Array
(
[2] => /Volumes/SAMPLES/ VOCALS/ AcmeInc Club Vocals/
[3] => /Volumes/SAMPLES/ VOCALS/ AtomicInc Dance Vocals/
[4] => /Volumes/SAMPLES/ VOCALS/ AFRICA/ AfroInc Zulu Vocals/
[5] => /Volumes/SAMPLES/ VOCALS/ AFRICA/ SampleInc Warriors/
)

关于PHP preg_grep 反向匹配模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33288321/

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