【问题标题】:Select substring after specific word在特定单词之后选择子字符串
【发布时间】:2015-06-22 11:34:46
【问题描述】:

从这样的字符串

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

我只需要选择源,所以src="the string I need"之间的单词

我尝试过使用 IndexOf 单词 src=" 但链接没有固定数量的字符来设置结尾。

【问题讨论】:

  • 你也应该在找到 src=" 后搜索 "
  • 您必须在服务器端执行此操作吗?如果是这样,请不要使用魔术字符串,请考虑使用 HTMLAgilityPack
  • 你可以控制这个 iframe 吗?我的意思是你会添加这个或者这个会从其他地方添加?

标签: c# html asp.net regex string


【解决方案1】:

如果您尝试解析一些 HTML 代码 - 使用 HTMLAgilityPack 可能会更好。

但在这种情况下,它只是您从某个地方获得并想要解析的一组字符串 - 您也可以使用 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;

【讨论】:

    【解决方案2】:

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

    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 =" 这样的边缘情况,但会给你一个开始的地方。显然这也是一个可以用正则表达式解决的问题;我会留给其他人来回答。

    【讨论】:

      【解决方案3】:

      我很想将所有属性拆分成一个数组,因为以后我可能还想要其他一些属性。在这样做时,它还可以轻松访问“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);
      

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

      【讨论】:

        猜你喜欢
        • 2020-12-30
        • 2014-10-03
        • 1970-01-01
        • 2018-09-30
        • 2016-05-05
        • 2020-10-25
        • 1970-01-01
        • 2018-08-14
        • 1970-01-01
        相关资源
        最近更新 更多