c# - C# 在 httpwebresponse 中查找字符串
问题描述
所以我试图从我的 httpwebresponse 中查找并获取一个字符串,我已经创建了一个流并且可以成功地从输出中读取以识别响应中的文本,但是现在我正在尝试从响应中提取文本,例如:
输出包含,
<script>
var Site = 'home';
var Home = {
page: 24,
name: 'Pokemon',
Title: Pokemon chars
};
</script>
我想做的只是提取
Pokemon
但是这可能会在各个页面上发生变化,所以我不能只是假设
name:
包含口袋妖怪
所以我需要做的是修剪名称但保留内部文本,所以我尝试过的内容类似于
string str5 = "name: '";
foreach (string str6 in str3.Split(new char[] {'\n'})) // str3 is = to the response given from the request which is now obviously a string its self.
{
if (str6.StartsWith(str5))
{
str4 = str6.Replace(str5, "").Replace("',", "");
}
}
哪个应该找到包含“名称:”的行,然后将“名称:”替换为什么都没有,并且该行的末尾相同,只留下字符串
Pokemon
但它似乎没有工作?
解决方案
如果您无法反序列化 JSON,则一种选择是使用正则表达式。
string output = @"<script>
var Site = 'home';
var Home = {
page: 24,
name: 'Pokemon',
Title: Pokemon chars
};
</script>";
string regexPattern = @"name:\s'(.+?)',";
Regex reg = new Regex(regexPattern);
var match = reg.Match(output);
if (match.Success)
{
Console.WriteLine(match.Groups[1].Value);
}
您正在捕获name: '
和',
使用正则表达式模式之间的所有内容。
推荐阅读
- php - 在 Magento 2 中开票,得到“我们现在无法保存发票”和“回滚交易尚未正确完成”
- python - 为什么 nohup 在 os.system 中的 python 脚本中不起作用?
- php - 如何使用 OneToMany 关系上的内置计数约束来验证新的子实体?
- ios - 我的文件没有被修改。为什么 Git 仍然告诉我它已更改
- python - 如何使用 -a +b 输入操作
- node.js - 如何开发自定义护照本地身份验证策略以与我的 REST API 一起使用
- spring-boot - 升级到 Spring Boot 2.4 会导致 GrantedAuthoritiesMapper 停止使用 OAuth
- javascript - Chrome 扩展图像更改不持久
- flutter - Flutter 中的 DropdownButton 溢出
- optaplanner - 多台机器同时完成任务