【问题标题】:Regex for extracting certain part of a String用于提取字符串的某些部分的正则表达式
【发布时间】:2011-04-13 14:29:53
【问题描述】:

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

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

我想只提取带有扩展名的文件名。
我对正则表达式的了解不多,所以我希望在这里得到一些帮助。 谢谢!

【问题讨论】:

  • 对acpet rate的了解也不多:)
  • 在您的示例中,文件名是“music mix.mp3”吗?
  • 是的。顺便说一句,这是一个列表框项

标签: c# .net regex


【解决方案1】:

请检查这个例子:

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

【讨论】:

  • +1。可能值得在开头添加^ 来锚定它;这将使正则表达式更有效率。
【解决方案2】:

使用正则表达式环视功能的解决方案。

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);

Example code here

【讨论】:

    【解决方案3】:

    这是正则表达式

    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);
    

    【讨论】:

      猜你喜欢
      • 2017-08-23
      • 1970-01-01
      • 2021-07-12
      • 2012-05-26
      • 2013-01-07
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      • 1970-01-01
      相关资源
      最近更新 更多