PCRE:搜索未注释的字符串或注释块内?

时间:2014-10-17 19:52:35

标签: regex pcre

我正在进行(PCRE)搜索字符串,但我不想匹配任何已注释或显示在注释块中的字符串,因此,在此文件中:

/*
  function someFuncInCommentBlock(){
      return 'match this string';
  }
*/
// var someVarThatsCommented = 'match this string';
var someVar = 'match this string';

function someFunc(){
    return 'match this string';
}

...我只希望看到match this string的两个匹配项(评论中的最后两个匹配项)。我需要什么样的模式语法呢?

1 个答案:

答案 0 :(得分:3)

您可以使用此正则表达式:

/\*[\s\S]*?\*/(*SKIP)(*FAIL)|//.*(*SKIP)(*FAIL)|'(.*?)'

<强> Working demo

enter image description here

这个正则表达式的想法与您不想要的相匹配,并使用标记(*SKIP)(*FAIL)将其丢弃。使用这种技术通常命名为&#34;丢弃技术&#34;您使用要排除的一系列模式执行以下操作:

/\*[\s\S]*?\*/(*SKIP)(*FAIL)     <--- Discard everything block comments
|                                or
//.*(*SKIP)(*FAIL)               <--- Discard everything single comments
|                                or
'(.*?)'                          <--- Keep everything withing single quotes

如果是PCRE正则表达式,您可以利用(*SKIP)(*FAIL)的优势说明排除与此模式匹配的所有内容

另一方面,不支持这些标志的正则表达式引擎可以通过使用由以下OR模式组成的正则表达技巧来实现相同的丢弃技术:

exclude this | another pattern to exclude | (save this content)

对于我发布的正则表达式,如果你必须在其他正则表达式引擎中实现相同,你可以使用这个正则表达式:

/\*[\s\S]*?\*/|//.*|'(.*?)'

要排除的所有模式都在左侧,它们由OR分隔。对于最正确的一方,你有一个匹配你想要的捕获组。一个简单的方法是使用debuggex图:

Regular expression visualization

正如 Bark Kiers 在此评论中所指出的,我的正则表达式将匹配单引号内的内容,它不会显式匹配match this string。因此,为了匹配match this string,您可以将正则表达式更改为:

/\*[\s\S]*?\*/(*SKIP)(*FAIL)|//.*(*SKIP)(*FAIL)|match this string
相关问题