【问题标题】:How can i get the numbers from a text part using indexof and substring or maybe HtmlAgilityPack?如何使用 indexof 和 substring 或者 HtmlAgilityPack 从文本部分获取数字?
【发布时间】:2017-02-13 12:37:40
【问题描述】:

我正在尝试使用第一个 indexof 和 substring。

在我下载的 html 文件中,我有这部分文本:

var arrayImageTimes = [];
arrayImageTimes.push('201702130145');arrayImageTimes.push('201702130200');arrayImageTimes.push('201702130215');arrayImageTimes.push('201702130230');arrayImageTimes.push('201702130245');arrayImageTimes.push('201702130300');arrayImageTimes.push('201702130315');arrayImageTimes.push('201702130330');arrayImageTimes.push('201702130345');arrayImageTimes.push('201702130400');

我想提取到一个列表或数组中,只有数字意味着最后我将有一个字符串列表:

201702130145
201702130200
201702130215

每个''之间的所有数字

我试过了:

public void ExtractDateAndTimes(string f)
        {
            string startTag = "var arrayImageTimes = [];";
            string endTag = "</script>";
            int startTagWidth = startTag.Length;
            int endTagWidth = endTag.Length;
            int index = 0;
            while (true)
            {
                index = f.IndexOf(startTag, index);
                if (index == -1)
                {
                    break;
                }
                // else more to do - index now is positioned at first character of startTag
                int start = index + startTagWidth;
                index = f.IndexOf(endTag, start + 1);
                if (index == -1)
                {
                    break;
                }
                // found the endTag
                string g = f.Substring(start, index - start);
            }
        }

在构造函数中:

string text = File.ReadAllText(@"c:\Temp\testinghtml.html");
ExtractDateAndTimes(text);

但我得到的只是我在上面添加的 var arrayImageTimes 的文本块。

【问题讨论】:

  • 为什么201702130230之类的结果中没有一些数字?
  • @CodingYoshi 你说得对。我只是通过解析数字举例说明了我的意思。但它应该解析所有这些,而不仅仅是我显示的结果。

标签: c# .net winforms


【解决方案1】:

使用Regex 使用Named matched subexpression 将所有匹配项查找到命名捕获组中:

// Don't forget to escape full stops!
// Capture quoted values inside round braces into imageTime capturing group
Regex regex = new Regex(@"arrayImageTimes\.push\('(?<imageTime>\d+)'\)", RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase | RegexOptions.Singleline);

MatchCollection matches = regex.Matches(myString);

List<string> timestamps = new List<string>();

foreach (Match m in matches)
{
    timestamps.Add(m.Groups["imageTime"].Value);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    • 2021-01-09
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多