How to extract specific part of string from text file ?

Chocolade 536 Reputation points
2022-09-01T07:23:29.69+00:00
string[] files = Directory.GetFiles(@"D:\Text Files\");  
            foreach (string file in files)  
            {  
                var list = GetLinks(File.ReadAllText(file));  
            }  

The GetLinks method :

public List<string> GetLinks(string message)  
        {  
            List<string> list = new List<string>();  
            string txt = message;  
            foreach (Match item in Regex.Matches(txt, @"(http|ftp|https):\/\/([\w\-_]+(?:(?:\.[\w\-_]+)+))([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?"))  
            {  
                if (item.Value.Contains("thumbs"))  
                {  
                    list.Add(item.Value);  
                }  
            }  
  
            return list;  
        }  

The result is links like that for example :

https://thumbs.something.com/thumbs/8/2/1/7/7/82177961a502cacfe75.mp4/82177961a502cacfe75.mp4-3.jpg

but i want to get only the first mp4 part :

https://thumbs.something.com/thumbs/8/2/1/7/7/82177961a502cacfe75.mp4

is there a simple way to do it inside the GetLinks method ?

Developer technologies C#
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Chocolade 536 Reputation points
    2022-09-01T07:28:33.107+00:00

    I did it with indexof and substring and it's working fine at least for my case :

    public List<string> GetLinks(string message)  
            {  
                List<string> list = new List<string>();  
                string txt = message;  
                foreach (Match item in Regex.Matches(txt, @"(http|ftp|https):\/\/([\w\-_]+(?:(?:\.[\w\-_]+)+))([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?"))  
                {  
                    if (item.Value.Contains("thumbs"))  
                    {  
                        int index1 = item.Value.IndexOf("mp4");  
                        if (index1 != -1)  
                        {  
                            string result = item.Value.Substring(0, index1 + 3);  
                            list.Add(result);  
                        }  
                    }  
                }  
      
                return list;  
            }  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.