2

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

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

一个例子,假设我想要“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”,或者它之前的所有内容,所以更简单的正则表达式可以完美地工作。对于我需要的东西,它是完美的,因为我只需要使用未注释的字符串(不一定是确切的字符串)物理定位 LINES,然后对它们进行注释,并且由于我的编辑器(Notepad++)允许我使用简单的快捷方式来注释/取消注释(Ctrl+Q),我只需要使用正则表达式搜索行,在它们之间跳转(使用 F3)并按 Ctrl+Q 对它们进行评论或在我仍然需要它们时保留它们。

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

4

2 回答 2

5

如果lookbehinds可以接受不确定的wifth表达式,您将能够在PHP中使用lookbehinds,但您实际上并不需要lookbehinds :) 前瞻可以做:

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

正则表达式101演示

\K重置匹配。

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

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

正则表达式101演示

或者

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

附录:

如果您还想mystring在同一行中获取倍数,请替换^by(?:\G|^)

\G上一场比赛结束时的比赛。

于 2013-10-11T19:18:38.863 回答
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 
"
  }
}
于 2013-10-11T19:16:56.467 回答