Regex to remove file path

问题: I want to remove some part of this file path: C:UsersroomDesktopdevmyappnode/data//test/nested/74201820018PM-AI2.jpg I want the path name after the 'data' like /...

问题:

I want to remove some part of this file path:

C:UsersroomDesktopdevmyappnode/data//test/nested/74201820018PM-AI2.jpg

I want the path name after the 'data' like /test/nested/74201820018PM-AI2.jpg

Edit: This file path comes from windows OS. I want regex to work for both windows or linux.


回答1:

You just need to use a regex with a matching group, something like this:

//data/(.+)$/

Explanation:

  • / matches the character / literally (case sensitive)
  • data matches the characters data literally (case sensitive)
  • / matches the character / literally (case sensitive)

1st Capturing Group (.+)

  • .+ matches any character (except for line terminators) - Quantifier — + Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

  • $ asserts position at the end of the string, or before the line terminator right at the end of the string (if any)

Note:

To make it compatible with both Windows and Linux paths you need to update the regex so it takes both / and into account:

[/\]data[/\](.+)$

Demo:

var str = "C:UsersroomDesktopdevmyappnode/data//test/nested/74201820018PM-AI2.jpg";
var match = str.match(//data/(.+)$/);
console.log(match[1]);

EDIT:

To remove the first part of this file path

You can use an inversed regex to match the first part of the path and remove it from the string, using .replace(regex, ''):

^(.+[/\]data[/\])

Demo:

var str = `C:\Users\room\Desktop\dev\myapp\node/data//test/nested/74201820018PM-AI2.jpg`;

const regex = /^(.+[/\]data[/\])/;

var matched = str.replace(regex, '');
console.log(matched);


回答2:

Try this. It checks if the rest of the characters is preceded by the string data/

var str = "C:UsersroomDesktopdevmyappnode/data//test/nested/74201820018PM-AI2.jpg"; 
console.log(str.match(/(?<=data/).+$/)[0]);


回答3:

I'm afraid that:

  • data in your path may at some time change to other string,
  • the actual "cut point" is double slash (less likely to change).

So your code should:

  • match the initial part of the string, up to the double slash (including),
  • replace is with a single slash.

Something like: result = my_path.replace(/.*///,"/");

  • 发表于 2018-07-05 15:30
  • 阅读 ( 293 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除