row1:10016/Documents/abc.pdf
第2行:10016-10017/10017/Documents/folder1/folder2/xyz.pdf
我正在尝试检索从/Documents开始的所有字符,但没有最后一部分(文件名(
在第1行,我想检索/Documents/
在第2行,我想检索/Documents/folder1/folder2/
我试过
var temp1 = FullPath.split("/Documents/")[0];
var A_Fpath = temp1.split("/");
A_Fpath = A_Fpath[A_Fpath.length - 1];
一个简单的正则表达式就能完成任务:
//Documents.*//
/ start the regex
/ match literally a "/" (the is to escape the / reserved character)
Documents match literally the word "Documents" (case sensitive
.* match 0 or more characters (any characters)
/ match literally a "/"
/ end the regex
This works because regex will attempt to match the longest possible string
of characters that match the regex.
const row1 = "10016/Documents/abc.pdf";
const row2 = "10016-10017/10017/Documents/folder1/folder2/xyz.pdf";
const regex = //Documents.*//;
const val1 = row1.match(regex)[0];
const val2 = row2.match(regex)[0];
console.log(val1);
console.log(val2);
这里有一个Regex101链接来测试它,并查看有关此特定regex的更多信息。
如果javascript有一个成熟的正则表达式引擎,可以使用正的、非捕获的前瞻组来确定何时停止。
由于javascript缺乏这一点,因此简单、清晰、高效的方法是根本不使用正则表达式。算法很简单:
-
在源文本中查找[第一个/最左边]
/Documents
,然后查找 -
在源文本中查找
/
的最后/最右侧出现 -
处理以下两种特殊情况:
- 源字符串根本不包含
/Documents
,并且 - 最右边的
/
是/Documents
中的/
- 源字符串根本不包含
-
如果出现上述特殊情况,则返回所需的子字符串从CCD_ 11一直延伸到并包括最后一个CCD_ 12
像这样:
function getInterestingBitsFrom(path) {
const i = path.indexOf('/Documents');
const j = path.lastIndexOf('/');
const val = i < 0 ? undefined // no '/Documents' in string
: i === j ? path.slice(i) // last '/' in string is the '/' in '/Documents'
: path.slice(i, j+1) // '/Documents/' or '/Documents/.../'
;
return retVal;
}
这也有一个值得称赞的好处,那就是对于那些必须弄清楚你试图实现什么的人来说,它很容易理解。