用于提取String的某些部分的正则表达式
嘿我试图从字符串中提取某些信息。 字符串看起来像
名称: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);
解决方案使用正则表达式环视function。
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*(?[\w\s]+.\w{3})
如果文件名是空白,则此正则表达式返回组中的音乐mix.mp3
string strRegex = @"Name:\s*(?[\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);