简体   繁体   English

Javascript正则表达式:仅匹配最后一个模式

[英]Javascript Regular Expression: Only matching the last pattern

Context: I have some dynamically generated HTML which can have embedded javascript function calls inside. 上下文:我有一些动态生成的HTML,可以在其中嵌入嵌入式javascript函数调用。 I'm trying to extract the function calls with a regular expression. 我正在尝试使用正则表达式提取函数调用。

Sample HTML string: 示例HTML字符串:

 <dynamic html>

   <script language="javascript">
       funcA();
   </script>

 <a little more dynamic html>

   <script language="javascript">
       funcB();
   </script>

My goal is to extract the text "funcA();" 我的目标是提取文本“ funcA();”。 and "funcB();" 和“ funcB();” from the above snippet (either as a single string or an array with two elements would be fine). 从上面的代码片段开始(以单个字符串或包含两个元素的数组都可以)。 The regular expression I have so far is: 我到目前为止的正则表达式是:
var regexp = /[\\s\\S]*<script .*>([\\s\\S]*)<\\/script>[\\s\\S]*/gm;

Using html_str.replace(regexp, "$1") only returns "funcB();". 使用html_str.replace(regexp, "$1")仅返回“ funcB();”。

Now, this regexp works just fine when there is only ONE set of <script> tags in the HTML, but when there are multiple it only returns the LAST one when using the replace() method. 现在,当HTML中只有一组<script>标记时,此正则表达式可以正常工作,但是当有多个<script>标记时,使用replace()方法时,它仅返回LAST标记。 Even removing the '/g' modifier matches only the last function call. 即使删除'/ g'修饰符也仅匹配最后一个函数调用。 I'm still a novice to regular expressions so I know I'm missing something fundamental here... Any help in pointing me in the right direction would be greatly appreciated. 我仍然是正则表达式的新手,所以我知道我在这里缺少一些基本的知识。如果能为我指明正确的方向提供任何帮助,将不胜感激。 I've done a bit of research already but still haven't been able to get this issue resolved. 我已经进行了一些研究,但仍无法解决此问题。

Your wildcard matches are all greedy. 您的通配符匹配都很贪婪。 This means they will not only match what you expect, but as much as there possibly is in your code. 这意味着它们不仅将符合您的期望,而且将与您的代码中的期望值尽可能地匹配。

Make them all non-greedy ( .*? ) and it should work. 使它们全部为非贪婪( .*? ),它应该起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM