正则表达式,用于删除导致关键字的字符串的第一部分

Regular expression to remove first part of string leading to keyword

本文关键字:字符串 第一部 一部分 关键字 用于 删除 正则表达式      更新时间:2023-09-26

我觉得我快要有一个手掌到额头的时刻了,但我似乎无法让它发挥作用。

我有一个路径,我想删除它的开头,直到某个文件夹(它是不同的文件夹,但文件夹的名称总是相同的)。

因此,对于/path/to/templates/sometemplate.html,我希望字符串只是templates/sometemplate.html.(删除了'/path/to/')。我不能只在"/"上拆分并删除前两个,因为另一个路径可能是/yet/other/path/to/templates/sometemplate.html。。。。

顺便说一句,我在Grunt脚本中做这件事,所以我在看Javascript string.replacement().

有人知道怎么做吗?

这里并不需要regex,只需使用String方法即可:

var s = '/yet/another/path/to/templates/sometemplate.html';
var r = s.substr(s.indexOf('/templates/') + 1)
//=> templates/sometemplate.html
.*?(?=templates)

试试这个。由empty string替换。请参阅演示。

http://regex101.com/r/hQ1rP0/81