简体   繁体   English

正则表达式从字符串中提取路径/文件名

[英]Regular Expression to pull a path/filename from a string

Given an input string, I would like to get the output from this in the specified format: filename;path . 给定一个输入字符串,我想以指定的格式从中获取输出: filename;path

For the input string: 对于输入字符串:

/vob/TEST/.@@/main/ch_vobsweb/1/VOBSWeb/main/ch_vobsweb/4/VobsWebUI/main/ch_vobsweb/2/VaultWeb/main/ch_vobsweb/2/func.js

I expect this output string: 我期望这个输出字符串:

func.js;VOBSWeb/VosWebUI/VaultWeb/func.js

The filename is listed at the end of the whole string, and its path is supposed to be stripped using the characters after each numeric value (eg. /1/VOBSWeb/ and then /4/VobsWebUI and then /2/vaultWeb ) 文件名列在整个字符串的末尾,并且应该在每个数字值之后使用字符来删除文件名的路径(例如/1/VOBSWeb/ ,然后是/4/VobsWebUI ,然后是/2/vaultWeb

Related: 有关:
This is related to an earlier C# question, but this time using JavaScript: String manipulation 这与早期的C#问题有关,但是这次使用JavaScript: 字符串操作

Since I almost finished typing it in anyway, here's the condensed version: 由于无论如何我几乎都完成了输入,因此这里是精简版:

result = subject.replace(/\/?(?:[^\/\d]+\/)+\d+\/([^\/]+\/?)/g, "$1")
                .replace(/^.*\/([^\/]+)$/, "$1;$0");

Never mind ,this has been answered in an earlier post by Tim 没关系,蒂姆在较早的帖子中已经回答了

First, remove all the "uninteresting stuff" from the string. 首先,从字符串中删除所有“无趣的东西”。

Search for .*?/\\d+/([^/]+/?) and replace all with $1 搜索.*?/\\d+/([^/]+/?)并全部替换为$1

In C#: resultString = Regex.Replace(subjectString, @".*?/\\d+/([^/]+/?)", "$1"); 在C#中: resultString = Regex.Replace(subjectString, @".*?/\\d+/([^/]+/?)", "$1");

In JavaScript: result = subject.replace(/.*?\\/\\d+\\/([^\\/]+\\/?)/g, "$1"); 在JavaScript中: result = subject.replace(/.*?\\/\\d+\\/([^\\/]+\\/?)/g, "$1");

This will transform your string into 这会将您的字符串转换为

VOBSWeb/VobsWebUI/VaultWeb/func.js VOBSWeb / VobsWebUI / VaultWeb / func.js


Second, copy the filename to the front of the string. 其次,将文件名复制到字符串的开头。

Search for (.*/)([^/]+)$ and replace with $2;$1$2 搜索(.*/)([^/]+)$并替换为$2;$1$2

C#: resultString = Regex.Replace(subjectString, "(.*/)([^/]+)$", "$2;$1$2"); C#: resultString = Regex.Replace(subjectString, "(.*/)([^/]+)$", "$2;$1$2");

JavaScript: result = subject.replace(/(.*\\/)([^\\/]+)$/g, "$2;$1$2"); JavaScript: result = subject.replace(/(.*\\/)([^\\/]+)$/g, "$2;$1$2");

This will transform the result of the previous operation into 这会将上一个操作的结果转换为

func.js;VOBSWeb/VobsWebUI/VaultWeb/func.js func.js; VOBSWeb / VobsWebUI / VaultWeb / func.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM