我正在尝试以重复的方式匹配文件夹/文件 - 基于路径分隔符 /
。
正则表达式:
/^(?:music|pictures)\/tom(?:(?=\/)\/([\w\-]+(?:\s+[\w\-]+)*)|$)$/gm
上面正则表达式的说明:
// Match a base-directory called music/pictures
// Match if directory tom exist
// If delimiter was found, match delimiter and word-character and hypen (no spaces etc at the beginning)
// Match spaces, word-characters and hypen (no spaces etc at the end)
//If delimiter was not found, end string
//End string
每次找到分隔符 /
(正向先行),它也应该匹配其余条件。它工作得很好,除非子文件夹遇到正则表达式。
music/tom/foldername
music/tom/folder name
music/tom/foldername/folder2 <--- Does not match
如您所见,最后一条路径无法匹配。如何扩展/改进正则表达式以便也匹配子文件夹?
正则表达式演示:https://regex101.com/r/oG9bC3/1
最佳答案
您可以使用此正则表达式来获得您想要的内容
^(?:music|pictures)\/tom((?:\/(?:[\w-]+(?:[ ]+[\w-]+)*))+)$
<强> Regex Demo
注意
- 当您已经知道下一个字符需要什么时,就不需要先行查找。
-
在 **字符类
的 first/last 中使用时不需要转义。
关于JavaScript 正则表达式 : Match additionals based on path delimiter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38800041/