用于提取字符串的特定部分的正则表达式

本文关键字:正则表达式 定部 字符串 用于 提取 | 更新日期: 2023-09-27 17:49:54

嘿,我试图从字符串中提取某些信息。字符串看起来像

名称:music mix.mp3大小:2356KB

我想只提取扩展名的文件名。
我没有太多的知识在正则表达式,所以我希望得到一些帮助在这里。谢谢!

用于提取字符串的特定部分的正则表达式

请检查这个例子:

const string str = "Name: music mix.mp3 Size: 2356KB";
var match = Regex.Match(str, "Name: (.*) Size:");
Console.WriteLine("Match: " + match.Groups[1].Value);

使用正则表达式查找功能的解决方案。

String sourcestring = "Name: music mix.mp3 Size: 2356KB";
Regex re = new Regex(@"(?<=^Name: ).+(?= Size:)");
Match m = re.Match(sourcestring);
Console.WriteLine("Match: " + m.Groups[0].Value);

这里的示例代码

这是正则表达式

Name:'s*(?<FileName>['w's]+.'w{3})

如果文件名带有空格

,则此正则表达式返回group中的音乐mix.mp3。
       string strRegex = @"Name:'s*(?<FileName>['w's]+.'w{3})";
        Regex myRegex = new Regex(strRegex);
        string strTargetString = @"Name: music mix.mp3 Size: 2356KB";
        Match myMatch = myRegex.Match(strTargetString);
        string fileName = myMatch.Groups["FileName"].Value;
        Console.WriteLine(fileName);