繁体   English   中英

JavaScript 没有前导或尾随斜线的路径正则表达式

[英]JavaScript Regex for Path without leading or trailing slashes

我正在努力找出 JavaScript 的正则表达式模式,该模式将修剪其前后斜杠(或哈希/扩展)的路径

例如:

path/
/path
/folder/path/
/folder/folder/path
/folder/path#hash
/folder/path.ext

应该返回:

path
path
folder/path
folder/folder/path
folder/path
folder/path

我觉得我正在接近以下内容,但它只选择没有任何斜杠、散列或句点的文本。

^([^\\\/\#\.]*)(?![\#\.\\\/].*$)/gm

我正在尝试在 vuetify 文本字段验证中将其用于正则表达式,如果这有帮助的话。

结果

我最终得到了这个正则表达式

/^(?![\#\/\.\$\^\=\*\;\:\&\?\(\)\[\]\{\}\"\'\>\<\,\@\!\%\`\~\s])(?!.*[\#\/\.\$\^\=\*\;\:\&\?\(\)\[\]\{\}\"\'\>\<\,\@\!\%\`\~\s]$)[^\#\.\$\^\=\*\;\:\&\?\(\)\[\]\{\}\"\'\>\<\,\@\!\%\`\~\s]*$/

https://regexr.com/66ol9

这是在没有后视的情况下实现的(它们在 Safari:() 中仍然被拒绝:):

^(?![#\/.])(?!.*[#\/.]$).*

请参阅正则表达式证明 和...

解释

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
    [#\/.]                   any character of: '#', '\/', '.'
--------------------------------------------------------------------------------
  )                        end of look-ahead
--------------------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
    .*                       any character except \n (0 or more times
                             (matching the most amount possible))
--------------------------------------------------------------------------------
    [#\/.]                   any character of: '#', '\/', '.'
--------------------------------------------------------------------------------
    $                        before an optional \n, and the end of
                             the string
--------------------------------------------------------------------------------
  )                        end of look-ahead
--------------------------------------------------------------------------------
  .*                       any character except \n (0 or more times
                           (matching the most amount possible))

在开始时使用负面前瞻,在结束时使用负面回顾。

/^(?![#\/.]).*(?<![#\/.])$/

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM