【发布时间】:2020-06-06 01:19:16
【问题描述】:
输入:parent/123/child/grand-child
预期输出:child
尝试 1:(?<=\/parent\/\d*)(.*)(?=\/.*)
错误:lookbehind 中的量词使其宽度不固定,look behind 不接受 * 但我不知道数字的宽度,因此必须使用它
尝试 2:(有效,但 2 个衬垫):
const currentRoute='/parent/123/child/grand-child'
let extract = currentRoute.replace(/\/parent\/\d*/g, '');
extract = extract.substring(1, extract.lastIndexOf('/'));
console.log('Result', extract)
如何使用单行获得提取物,最好使用正则表达式
【问题讨论】:
-
为什么不使用捕获组而不是匹配?
console.log("parent/123/child/grand-child".match(/parent\/\d+\/(\w+)\/.*/)[1]); -
我知道你说的最好是正则表达式,但
.split("/")[2]也可以 -
@EugenSunic 查看 cmets 中的示例。
-
您可以在后视中使用量词,但这并未得到广泛支持。例如,它在 Chrome 和 Nodejs 中。
-
您可以将模式更新为
(?<=parent\/\d*\/)([^\/]+)(?=\/)并在 Chrome 中查看 regex101.com/r/CA7LNH/1 请注意,可以省略末尾前瞻中的.*。
标签: javascript regex