简体   繁体   English

在C#中重命名文件需要正则表达式

[英]Regex required for renaming file in C#

I need a regex for renaming file in c#. 我需要一个正则表达式来重命名c#中的文件。 My file name is 22px-Flag_Of_Sweden.svg.png . 我的文件名为22px-Flag_Of_Sweden.svg.png I want it to rename as sweden.png . 我希望将其重命名为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. 我想提取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: 我不确定在c#中的外观(尽管正则表达式很重要,而不是语言),但是在Java中,它看起来像这样:

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 :) 我希望我现在对C#有所了解:)

Cheers Eugene. 干杯尤金。

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

I don't know c# but the regex could be: 我不知道C#,但是正则表达式可能是:

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

and the replace part is : $1.png 替换部分为: $1.png

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

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