简体   繁体   中英

Regex required for renaming file in C#

I need a regex for renaming file in c#. My file name is 22px-Flag_Of_Sweden.svg.png . I want it to rename as sweden.png .

So for that I need regex. Please help me.

I have various files more than 300+ like below:

22px-Flag_Of_Sweden.svg.png   - should become sweden.png
13px-Flag_Of_UnitedStates.svg.png  - unitedstates.png
17px-Flag_Of_India.svg.png - india.png
22px-Flag_Of_Ghana.svg.png - ghana.png

These are actually flags of country. I want to extract Countryname.Fileextension. Thats all.

var fileNames = new [] {
    "22px-Flag_Of_Sweden.svg.png"
    ,"13px-Flag_Of_UnitedStates.svg.png"
    ,"17px-Flag_Of_India.svg.png"
    ,"22px-Flag_Of_Ghana.svg.png"
    ,"asd.png"
};

var regEx = new Regex(@"^.+Flag_Of_(?<country>.+)\.svg\.png$");



foreach ( var fileName in fileNames )
{
    if ( regEx.IsMatch(fileName))           
    {
        var newFileName = regEx.Replace(fileName,"${country}.png").ToLower();
        //File.Save(Path.Combine(root, newFileName));

    }
}

I am not exactly sure how this would look in c# (although the regex is important and not the language), but in Java this would look like this:

String input = "22px-Flag_Of_Sweden.svg.png";
Pattern p = Pattern.compile(".+_(.+?)\\..+?(\\..+?)$");
Matcher m = p.matcher(input);

System.out.println(m.matches());

System.out.println(m.group(1).toLowerCase() + m.group(2));

Where the relevant for you is this part :

  ".+_(.+?)\\..+?(\\..+?)$"

Just concat the two groups.

I wish I knew a bit of C# right now :)

Cheers Eugene.

这将返回第一个捕获组中的国家: ([a-zA-Z]+)\\.svg\\.png$

I don't know c# but the regex could be:

^.+_(\pL+)\.svg\.png

and the replace part is : $1.png

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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