用正则表达式忽略标签和javascript

问题描述 投票:-1回答:2

我正在尝试在下面的HTML上执行正则表达式替换。我正在使用一个现有的(我没有写它并且没有真正理解它)正则表达式模式忽略HTML标记内的任何内容,但我需要它也忽略脚本标记之间的任何内容。模式是(?<!<[^>]*)(diversity|and|inclusion)。问题是,javascript中的和'playerBrandingId'正在匹配并最终被替换。如果重要,我正在使用C#。 You can see what I get here.

<p>When it comes to building more diverse and inclusive workforces, the sports industry is already a leader, but it can do much more. One of the ways SBD/SBJ is focusing on diversity and inclusion is by talking to business leaders about what the industry can do better. In our first video in the &ldquo;SBJ Diversity and Inclusion&rdquo; series, we hear from execs working in leagues, technology, recruitment and academia.</p>
<div class="article-offset-block article-video article-offset-block--half">    
  <div class="u-vr2">
    <div id='video-F17F523A70EB43ECAF54DF46144835B4'></div>
  </div>
</div>
<script>
  var playerParam = {
    'pcode': 'poeXI63BtIsR_ugBoy3Z6X8KfiMo',
    'playerBrandingId': 'video-F17F523A70EB43ECAF54DF46144835B4',        
    'autoplay': false,
    'loop': false
  };
  OO.ready(function () { window.ppF17F523A70EB43ECAF54DF46144835B4 = OO.Player.create('video-F17F523A70EB43ECAF54DF46144835B4', 'w5cW9qZTE6qRRDqfBdi861XWJTXci9uE', playerParam); });
</script>

编辑:

模式是由用户的查询生成的,因此模式可以包含单词windowplayer,当我更改模式以包含\b时,它将在javascript中匹配:(?<!<[^>]*)\b(window|player|and)\b

Another example

regex
2个回答
1
投票

将正则表达式更改为(?<!<[^>]*)\b(diversity|and|inclusion)\b \b添加了对单词边界的测试。强迫()中的每个单词都是完整的单词。

编辑:你试图解析HTML提取文本节点,然后检查它们,你不应该在任何情况下尝试用正则表达式解析HTML除非你想调用rite 666 Ph'nglui mglw'nafh Cthulhu R'lyeh wgah'nagl fhtagn。

使用HTML解析库查看this page的某些方法,或者使用.NET和C#搜索从HTML中提取文本节点


0
投票

答案是,根据this,你无法做我正在尝试用Regex做的事情。

© www.soinside.com 2019 - 2024. All rights reserved.