user3541092
user3541092

Reputation: 297

Rename file using regular expressions in .NET?

Is possible to write a regular expression, with the following file names as the input:

4214690028_6.mp3
178146230886_001.waV
178146230886_999.Wav
178146230886_0001.mP3
NoUnderscore3088003.wav

where the string output is as follows:

6_4214690028.mp3
001_178146230886.waV
999_178146230886.Wav
0001_178146230886.mP3
NoUnderscore3088003.wav - Not touched

Just wondering if this is even feasible using nothing but the .NET Regex class..

Upvotes: 0

Views: 71

Answers (2)

vks
vks

Reputation: 67988

(.*?)_(.*?)(?=\.)

Try this.Replace by $2_$1.See demo.

http://regex101.com/r/hQ1rP0/47

Upvotes: 0

hwnd
hwnd

Reputation: 70732

Yes, if you must use a regular expression it could be done.

String s = "4214690028_6.mp3";
String r = Regex.Replace(s, @"^(\d+)_(\d+)\.([^.]+)$", "$2_$1.$3");
Console.WriteLine(r); // => "6_4214690028.mp3"

Regex Explanation

Upvotes: 2

Related Questions