如何从特定字符串中提取时间
本文关键字:提取 取时间 字符串 | 更新日期: 2023-09-27 18:37:01
我的代码是:
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
我如何仅从部分中提取所有内容:var imageUrls = ["........
由于在f
内部还有其他地方,因此我只需要从 var imageUrls = [" 并以 "] 结尾的部分中提取它;
这就是我要做的。这不是一个纯粹的解决方案,但它有效。
(下面假设您的数据格式在合理的时间段内保持完全相同。如果管理源代码的人发生变化,这段代码就会中断!
- 对模式"var imageUrls = [ ... ];"进行正则表达式匹配,并将其移动到单独的字符串中。
- 从这里,切掉
var imageUrls = [
并从绳子上];
。
路径 A:
- 使用
string.split()
创建 url 字符串的数组。 - 通过字符串运行 for 循环并将它们分配给 Uri 类(例如:
myUri
)。现在,您可以通过HttpUtility.ParseQueryString(myUri.Query).Get("time");
获取每个查询字符串变量的值部分
路径 B:
- 还要砍掉"/image2.ashx?region=is&time="和"&ir=false",只留下你真正想要的东西。
步骤:
- 使用 HtmlAgilityPack 获取 HTML 并提取特定的
<script>
标签。 - 可能该脚本块可以仅与正则表达式甚至基本
String.IndexOf
匹配以删除URL列表 - 只需使用
String.Split
列表即可切入唯一一次 - 对于每个 Url,使用 Uri 类提取
Uri.Query
部分,然后从 Uri 获取单个查询参数
注意:如果 JavaScript 太复杂,您可能需要获取真正的 JavaScript 解析器...
要匹配时间使用:
(?!/image2'.ashx'?region=is&time)'d+(?=&ir=false)
演示