如何从特定字符串中提取时间?

How can i extract times from specific string?

我的代码是:

htmltoextract = new Uri("http://test");

client = new WebClient();
f = client.DownloadString(htmltoextract);
client.Dispose();
string pattern = @"(\d{12})";
Regex ex = new Regex(pattern, RegexOptions.Singleline);

MatchCollection matches = ex.Matches(f);
IFormatProvider provider = CultureInfo.InvariantCulture;
List<DateTime> dateTime = new List<DateTime>();
foreach (Match match in matches)
{
     dateTime.Add(DateTime.ParseExact(match.Value, "yyyyMMddHHmm", provider));
}

f里面的某处我有这条线:

var imageUrls = ["/image2.ashx?region=is&time=201501102145&ir=false","/image2.ashx?region=is&time=201501102130&ir=false","/image2.ashx?region=is&time=201501102115&ir=false","/image2.ashx?region=is&time=201501102100&ir=false","/image2.ashx?region=is&time=201501102045&ir=false","/image2.ashx?region=is&time=201501102030&ir=false","/image2.ashx?region=is&time=201501102015&ir=false","/image2.ashx?region=is&time=201501102000&ir=false","/image2.ashx?region=is&time=201501101945&ir=false"];

我需要将它提取两次到两个列表中:

第一个列表是日期时间

第二个列表应该是字符串,并且应该将其添加到其中:

/image2.ashx?region=is&time=201501102145&ir=false
/image2.ashx?region=is&time=201501102130&ir=false
/image2.ashx?region=is&time=201501102115&ir=false
/image2.ashx?region=is&time=201501102100&ir=false
/image2.ashx?region=is&time=201501102045&ir=false
/image2.ashx?region=is&time=201501102030&ir=false
/image2.ashx?region=is&time=201501102015&ir=false
/image2.ashx?region=is&time=201501102000&ir=false
/image2.ashx?region=is&time=201501101945&ir=false

我有两个问题:

如何提取时间和字符串 /image2.ashx?region=is&time=201501101945&ir=false

如何仅从 part:var imageUrls = [".......

中提取所有内容

因为在 f 里面还有其他地方,这次我只需要从 var imageUrls = [" 和 "];

开始的部分提取它

步骤:

  • 使用 HtmlAgilityPack 获取 Html 并提取特定的 <script> 标签。
  • 脚本块可能只与 reg-ex 或什至基本 String.IndexOf 匹配以删除 url 列表
  • 只有 Url 的列表使用 String.Split 切割成唯一一次
  • 对于每个 Url 使用 Uri class 提取 Uri.Query 部分然后 Get individual query parameters from Uri

注意:如果 JavaScript 太复杂,您可能需要获得真正的 JavaScript 解析器...

这就是我会做的。这不是一个纯粹的解决方案,但它确实有效。

(以下假设您的数据格式在合理的时间段内保持完全相同。如果管理源代码的人员发生变化,则此代码将中断!)

  1. 对模式进行正则表达式匹配 "var imageUrls = [ ... ];" 并将其移动到单独的字符串。
  2. 据此,从字符串中删除 var imageUrls = [];

路径A:

  1. 使用 string.split(),创建 url 个字符串的数组。
  2. 运行 对字符串进行 for 循环并将它们分配给 Uri class(例如:myUri)。您现在可以通过 HttpUtility.ParseQueryString(myUri.Query).Get("time");
  3. 获取每个查询字符串变量的值部分

路径 B:

  1. 同时去掉“/image2.ashx?region=is&time=”和“&ir=false”,只留下你真正想要的。

要匹配时间使用:

(?!/image2\.ashx\?region=is&time)\d+(?=&ir=false)

DEMO