【问题标题】:Javascript Regex: Match additionals based on path delimiterJavascript Regex:根据路径分隔符匹配附加项
【发布时间】:2016-08-06 02:33:10
【问题描述】:

我正在尝试以重复方式匹配文件夹/文件 - 基于路径分隔符 /

正则表达式:

/^(?: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

【问题讨论】:

  • 所以你想匹配tom之后的所有内容?
  • 早上好@rock321987,是的,这是正确的。我想匹配 tom 之后的所有内容(开头/结尾处的空格除外),并且仅在找到分隔符时才匹配。
  • 看看 this 是否有效..我已将 \s 替换为空格,因为 \s 匹配新行
  • 扎实的工作@rock321987!非常感谢您的帮助。如果您愿意,请将此作为官方答案发布,以便我给您点赞。

标签: javascript regex regex-greedy


【解决方案1】:

你可以使用这个正则表达式来得到你想要的

^(?:music|pictures)\/tom((?:\/(?:[\w-]+(?:[ ]+[\w-]+)*))+)$

Regex Demo

注意

  • 当您已经知道下一个字符需要什么时,就不需要前瞻了。
  • -在**character classfirst/last中使用时不需要转义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-22
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    相关资源
    最近更新 更多