【问题标题】:How do I see if a string contains another string with quotes in it?如何查看一个字符串是否包含另一个带引号的字符串?
【发布时间】:2018-02-02 17:40:22
【问题描述】:

我正在尝试查看一个大字符串是否包含这行 HTML:

<label ng-class="choiceCaptionClass" class="ng-binding choice-caption">Was this information helpful?</label>

如您所见,这个 sn-p 在多个地方都有引号,当我执行以下操作时会导致问题:

Assert.IsTrue(responseContent.Contains("<label ng-class="choiceCaptionClass" class="ng - binding choice - caption">Was this information helpful?</label>"));

我已经尝试了这两种定义字符串的方法:

@"<label ng-class=""choiceCaptionClass"" class=""ng - binding choice - caption"">Was this information helpful?</label>"

"<label ng-class=\"choiceCaptionClass\" class=\"ng - binding choice - caption\">Was this information helpful?</label>"

但在每种情况下, Contains() 方法都会查找带有双引号或反斜杠的文字字符串。有没有另一种方法可以定义这个字符串,以便我可以正确搜索它?

【问题讨论】:

  • 用正则表达式试试
  • 不可以使用HTML Agility Pack 吗?它为您处理搜索/解析 HTML。这样你就不必自己动手了。
  • 好主意,我忘记使用敏捷包了。我将把它包括在我接下来的工作中。

标签: c# html string


【解决方案1】:

尝试使用正则表达式。我为你做了这个,但你可以测试你自己的正则表达式here

var regex = new Regex(@"<label\s+ng-class\s*=\s*""choiceCaptionClass""\s+class\s*=\s*""ng-binding choice-caption""\s*>\s*Was this information helpful\?\s*</label>", RegexOptions.IgnoreCase);
Assert.IsTrue(regex.IsMatch(responseContent));

如果这不起作用,请使用测试工具找出模式的哪一部分正在消失。

希望对您有所帮助!

【讨论】:

    【解决方案2】:

    用反斜杠转义双引号是正确的做法。

    您的搜索可能失败的原因是字符串实际上并不匹配。例如,在带有反斜杠的版本中,一些破折号周围有空格,但 HTML 字符串没有。

    【讨论】:

      猜你喜欢
      • 2021-05-06
      • 2013-03-13
      • 2015-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多