Javascript 正则表达式:根据路径定界符匹配附加项
Javascript Regex: Match additionals based on path delimiter
我正在尝试以重复的方式匹配 folders/files - 基于路径定界符 /
。
正则表达式:
/^(?: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
如您所见,最后一条路径无法匹配。我怎样才能 extend/improve 正则表达式来匹配子文件夹?
正则表达式演示:https://regex101.com/r/oG9bC3/1
你可以使用这个正则表达式来得到你想要的
^(?:music|pictures)\/tom((?:\/(?:[\w-]+(?:[ ]+[\w-]+)*))+)$
注意
- 当你已经知道你需要什么作为下一个字符时,你不需要先行。
-
在**character class
. 的first/last中使用时不需要转义
我正在尝试以重复的方式匹配 folders/files - 基于路径定界符 /
。
正则表达式:
/^(?: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
如您所见,最后一条路径无法匹配。我怎样才能 extend/improve 正则表达式来匹配子文件夹?
正则表达式演示:https://regex101.com/r/oG9bC3/1
你可以使用这个正则表达式来得到你想要的
^(?:music|pictures)\/tom((?:\/(?:[\w-]+(?:[ ]+[\w-]+)*))+)$
注意
- 当你已经知道你需要什么作为下一个字符时,你不需要先行。
-
在**character class
. 的first/last中使用时不需要转义