开发者

String manipulation in C#: strip a path using the characters after each numeric value

开发者 https://www.devze.com 2023-01-10 16:42 出处:网络
Given an input string, I would like to get the output from this in the specified format: filename;path.

Given an input string, I would like to get the output from this in the specified format: 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)


If the number of paths is arbitrary, then you need a two-step approach:


First, remove all the "uninteresting stuff" from the string.

Search for .*?/\d+/([^/]+/?) and replace all with $1.

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

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

This will transform your string into VOBSWeb/VobsWebUI/VaultWeb/func.js.


Second, copy the filename to the front of the string.

Search for (.*/)([^/]+)$ and replace with $2;$1$2.

C#: resultString = Regex.Replace(subjectString, "(.*/)([^/]+)$", "$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


If the number of paths is constant, then you can do it in a single regex:

Search for ^.*?/\d+/([^/]+/).*?/\d+/([^/]+/).*?/\d+/([^/]+/).*?/\d+/([^/]+)

and replace with $4;$1$2$3$4.

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

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

This regex will be inefficient if the string fails to match; this could be improved with atomic grouping, but JavaScript doesn't support that.


Javascript has a split() function on strings that returns an array, so I think that's probably a good starting point for what you're going for.


Assuming its not an arbitrary number of paths you can use regular expressions:

Find this:

.*[0-9]/([a-zA-Z]*)/[^0-9]*[0-9]/([a-zA-Z]*)/[^0-9]*[0-9]/([a-zA-Z]*)/[^0-9]*[0-9]/([a-zA-Z.]*)/

Then use the groupings to write the new string:

\4;\1/\2/\3/\4
0

精彩评论

暂无评论...
验证码 换一张
取 消