Regex for extracting certain part of a String

前端 未结 3 528
再見小時候
再見小時候 2020-12-01 21:39

Hey Im trying to extract certain information from a string. The String looks like

Name: music mix.mp3 Size: 2356KB

I w

相关标签:
3条回答
  • 2020-12-01 21:39

    Please check this example:

    const string str = "Name: music mix.mp3 Size: 2356KB";
    var match = Regex.Match(str, "Name: (.*) Size:");
    Console.WriteLine("Match: " + match.Groups[1].Value);
    
    0 讨论(0)
  • 2020-12-01 21:57

    This is regex

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

    this regex return the music mix.mp3 in group if the name of file is with white space

           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);
    
    0 讨论(0)
  • 2020-12-01 22:01

    Solution using regex lookaround feature.

    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

    0 讨论(0)
提交回复
热议问题