正则表达式查找未注释的字符串?

时间:2013-10-11 18:13:24

标签: php regex comments

我想要一个正则表达式来查找任何给定的字符串,但前提是它没有用单行注释进行注释。

我不介意它是否在多行注释中找到字符串(除此之外,我认为正则表达式会更复杂)。

一个例子,asumming我想要“mystring”(没有引号):

mystring bla bla bla <-- should find this
bla bla mystring bla <-- also this
// bla bla mystring <-- not this , because is already commented
//mystring <-- not this
//                alkdfjñas askfjña bla bla mystring <-- not this
wsfier mystring añljkfasñf <--should find this
mystring //a comment <-- should find this
 bla bla // asfsdf mystring <-- should SKIP this, because mystring is commented
/* 
asdfasf
mystring   <-- i dont care if it finds this, even if it is inside a block comment
añfkjañsflk
// aksañl mystring <-- but should skip this, because the single line is already commented with '//' (regardless the block comment) 

añskfjñas
asdasf
*/

换句话说,我只想查找mystring尚未用“//”注释的事件,即单行注释。 (再一次,我不关心多行注释)。

谢谢!

更新,我找到了一个简单的答案,比下面接受的答案更容易理解(无论如何也是如此)。

就像:^([^//]*)mystring

一样简单

因为我不在乎我是否只匹配“mystring”或之前的所有内容,所以更简单的Regex可以完美地运行。 对于我需要的东西,它是完美的,因为我只需要用未注释的字符串(不一定是确切的字符串)来物理定位LINES,然后对它们进行注释,并且因为我的编辑器(Notepad ++)允许我用简单的快捷方式注释/取消注释(Ctrl + Q),我只需要搜索带有正则表达式的行,在它们之间跳转(使用F3)并按Ctrl + Q来评论它们或者如果我仍然需要它们的话保留它们。

在这里试试http://regex101.com/r/jK2iW3

2 个答案:

答案 0 :(得分:4)

如果lookbehinds可以接受无限的wifth表达式,你可以在PHP中使用lookbehind,但你实际上并不需要lookbehinds :)前瞻可以做:

^(?:(?!//).)*?\Kmystring

regex101 demo

\K重置匹配项。

如果您突然希望通过说您不希望块内注释中的部分进一步推动这一点,您可以使用更多的前瞻:

^(?:(?!//).)*?\Kmystring(?!(?:(?!/\*)[\s\S])*\*/)

regex101 demo

^(?s)(?:(?!//).)*?\Kmystring(?!(?:(?!/\*).)*\*/)

附录:

如果您还希望在同一行中获得多个mystring,请将^替换为(?:\G|^)

\G在上一场比赛结束时匹配。

答案 1 :(得分:1)

$ example是您在字符串中提供的示例。

<?php 

// Remove multiline comments
$no_multiline_comments = preg_replace('/\/\*.*?\*\//s', '', $text);

// Remove single line comments
$no_comments = preg_replace("/\/\/.*?\n/", "\n", $no_multiline_comments);

// Find strings
preg_match_all('/.*?mystring.*?\n/', $no_comments, $matches);

var_dump($matches);

var_dump()的结果

array(1) {
  [0]=>
  array(4) {
    [0]=>
    string(43) "mystring bla bla bla <-- should find this
"
    [1]=>
    string(36) "bla bla mystring bla <-- also this
"
    [2]=>
    string(50) "wsfier mystring añljkfasñf <--should find this
"
    [3]=>
    string(10) "mystring 
"
  }
}
相关问题