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

JavaScript Regex for Path without leading or trailing slashes

我正在努力找出 JavaScript 的正则表达式模式,它将 trim 其前后斜杠(或 hashes/extensions)

的路径

例如:

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

应该return:

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

我觉得我已经接近以下内容了,但它只选择没有任何斜线、散列或句号的文本。

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

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

结果

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

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

https://regexr.com/66ol9

在开始时使用负前瞻,在结束时使用负后瞻。

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

DEMO

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

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

参见regex proof。还有...

解释

--------------------------------------------------------------------------------
  ^                        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))