提问者:小点点

在特定单词后选择子字符串


从这样的字符串

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

我只需要选择源,所以src=我需要的字符串之间的单词“

我尝试使用单词src=“的索引,但是链接没有固定的字符数来设置结尾。


共3个答案

匿名用户

如果您试图解析一些HTML代码--使用HTMLAGilitypack可能更好。

但在本例中,它只是您从某处获得的一组字符串,并且想要解析--您也可以使用正则表达式来完成:

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;

匿名用户

一个简单的实现,其中我假设您有一个字符串作为输入:

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
}

它肯定会漏掉边缘情况,比如,但会给你一个开始的地方。显然,这也是一个可以使用正则表达式解决的问题;我将把这个问题留给其他人来回答。

匿名用户

我很想把所有的属性拆分成一个数组,因为这是可能的,稍后我可能还想要其他的一些属性。在这样做时,它还可以方便地访问'src'属性。所以我会做这样的事:

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

这样做的好处是,您还可以在数组中拥有所有其他属性,如果需要,您可以将这些属性取出来。