Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

c#

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)

like image 416
Raj Avatar asked Mar 10 '26 18:03

Raj


1 Answers

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.

like image 77
Tim Pietzcker Avatar answered Mar 12 '26 08:03

Tim Pietzcker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!