使用JS正则表达式从字符串中获取路径的倒数第二个组件

4

给定字符串 '/root/hello/hello/world'

我想提取路径中倒数第二个组件,即hello的第二个出现。

如果不存在父级部分,则希望返回空。因此,字符串/world应返回一个空字符串或null。

如何使用正则表达式或类似方法提取最后一个路径组件?

语言是javascript。


我不理解,你的规则是什么?是倒数第二还是第二次出现?还是必须同时遵守这两个规则? - Rui Silva
1
倒数第二个 - 因此,给定文件名路径,获取父目录名。 - Richard G
"/world/"怎么样? - Rajesh
这个怎么样:链接 它应该会有所帮助。 - Rui Silva
为什么需要使用正则表达式?使用split给出的解决方案足够吗? - Rui Silva
可以的,分割字符串是可以的。 - Richard G
4个回答

3
你可以首先在斜杠字符上使用split方法将字符串转换为数组:
var split = '/root/hello/hello/world'.split('/')

-> ["", "root", "hello", "hello", "world"]

您可以获取倒数第二个项目:
var result = split[split.length - 2]

...但您可能需要先检查数组的长度:

var result;
if (split.length >= 2)
  result = split[split.length - 2]

我认为这是第一个,但我只能在8分钟后接受它。 - Richard G

3

您可以做:

let str = '/root/hello/hello/world';

let result = str.split('/');
console.log(result[result.length-2]);


当你有一个与被调用的函数同名的变量时,所选择的答案有点令人困惑。"split" 这个更容易理解。 - KingAndrew

1
使用正则表达式,如所请求的那样,您可以这样做:


([^/\n]*)\/[^/\n]*$

将倒数第二部分捕获到捕获组1中。

([^/\n]*) 部分(括号内)捕获不是 / 或换行符 (\n) 的一段字符。 \/ 确保其后跟着一个 /[^/\n]*$ 检查该行最后是否以另一个没有 /(或 LF)的字符串结束。

var pathArray = [
      '/root/hello/cruel/world',
      '/root/hello/world',
      '/root/world',
      '/world'
    ],
    re = /([^/\n]*)\/[^/\n]*$/;
    
pathArray.forEach(function (path) {
  document.write( '"' + path + '" returns "' + re.exec(path)[1] + '"<br/>' );
});

在regex101上尝试并实验它。


0

你不需要正则表达式,只需要分割它。

const string = '/root/hello/hello/world';

// Split by the '/' character
const stringSplit = string.split('/');

// Slice the array, taking only the last 2 items.
// Then select the first one in the array
const myVal = stringSplit.slice(-2)[0];

// OR, using length
const myValLen = stringSplit[stringSplit.length - 2];

// OR, in one
const myValShort = string.split('/').slice(-2)[0];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接