Select a substring after a specific word

From such lines

<iframe width="560" height="315" src="https://www.youtube.com/embed/KRFHiBW9RE8" frameborder="0" allowfullscreen></iframe> 

I need to select only the source, so the word between src = "the string I need"

I tried using IndexOf for the word src = ", but the link does not have a fixed number of characters to set the ending.

+6
source share
3 answers

If you are trying to parse HTML code, it is better to use HTMLAgilityPack .

But in this case, it’s just a set of lines that you got somewhere and want to parse - you can also do this using regular expressions :

 string s ="<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/KRFHiBW9RE8\" frameborder=\"0\" allowfullscreen></iframe>"; var match = Regex.Match(s, "src=\"(.*?)\""); string src; if (match.Success) src = match.Groups[1].Value; 
+10
source

A naive implementation in which I assume that you have a string as input:

 string input = "<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/KRFHiBW9RE8\" frameborder=\"0\" allowfullscreen></iframe>"; if (input.Contains("src=\"")) { string output = input.Substring(input.IndexOf("src=\"") + 5); // output is: https://www.youtube.com/embed/KRFHiBW9RE8" frameborder="0" allowfullscreen></iframe> output = output.Substring(0, output.IndexOf("\"")); // output is: https://www.youtube.com/embed/KRFHiBW9RE8 } 

This will certainly miss an extreme situation, such as src =" , but give you a place to start. Obviously, this is also a problem that can be solved with regular expressions; I will leave this for someone else to answer.

+4
source

I will be tempted to split all the properties into an array, as much as possible, maybe I would like some more. However, it will also provide easy access to the src property. So I would do something like this:

 string iFrameString = "<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/KRFHiBW9RE8\" frameborder=\"0\" allowfullscreen>"; //split properties based on spaces string[] tagProps = iFrameString.Split(new Char[]{' '}); //get the property out. string prop = "src=\""; string source = Array.Find(tagProps, x => x.StartsWith(prop, StringComparison.InvariantCultureIgnoreCase)); string ModifiedSource = source.Substring(prop.Length,source.Length - prop.Length); 

The advantage of this is that you have all the other properties in your array, and you can get them if necessary.

+2
source

Source: https://habr.com/ru/post/985245/


All Articles