首页 > 解决方案 > 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

但它似乎没有工作?

标签: c#httpwebrequesthttpwebresponse

解决方案


如果您无法反序列化 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: '',使用正则表达式模式之间的所有内容。


推荐阅读