1

如果出现 3 次或更多,我需要替换最后一个斜杠。如果我们有这样的路径"/foo/bar/",它应该变成"/foo/bar". "/foo/"但是不应该触及这样的路径。

我用转义的斜杠 ( \/) 和量词 ( {3,}) 进行了尝试:

/\/{3,}$/

然而,这个正则表达式只匹配紧跟在另一个之后的斜杠"/foo/bar///"

有什么想法可以解决这个问题吗?也许有正面/负面lookahead的?

http://www.regexr.com/393pm

可视化:

"/foo/"         => "/foo/"
"/foo/bar/"     => "/foo/bar"
"/foo/bar/baz/" => "/foo/bar/baz"

感谢FedeAvinash RajAmal Murali!由于性能很重要,@Fede 是赢家:http: //jsperf.com/match-last-slash-if-there-are-at-least-nth-occurrences

4

3 回答 3

2

您可以使用以下正则表达式:

\/.*?\/.*(\/)

这里有工作示例:

http://regex101.com/r/xT3pN1/2

正则表达式可视化

调试演示

如果要保留除最后一个斜杠以外的内容,可以使用此正则表达式并将第一组引用为\1

(\/.*?\/.*)(\/)

用替换检查工作示例:

http://regex101.com/r/xT3pN1/3

于 2014-07-03T17:34:55.377 回答
1

您可以使用以下正则表达式进行积极的前瞻:

^(?=.*(?:.*?\/){3,})(.*)\/$/m

解释:

^          # Assert position at the beginning of the line
(?=        # Positive lookahead: if followed by
  .*       # Match any number of characters
  (?:      # Begin non-capturing group
    .*?\/  # Match any number of characters followed by a '/'
  )        # End of group
  {3,}     # Repeat the group 3 or more times
)          # End of lookahead
(.*)       # Match (and capture) any number of characters
\/         # Match a literal backslash
$          # Assert position at the end of the line

然后将其替换为\1.

正则表达式 101 演示

于 2014-07-03T17:15:46.017 回答
1

这个怎么样?

^((?=\/.*?\/.*?\/).*?)([\/]+)$

用第一个捕获的组替换所有。

演示

于 2014-07-03T17:48:44.913 回答