嘿,我正在尝试从一个字符串中提取特定的信息。这个字符串看起来像:
名称: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);
^
以锚定它;这将使正则表达式更高效。 - SpudleyString 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})
如果文件名称中有空格,此正则表达式将返回音乐混合文件 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);