我想要一个正则表达式来查找任何给定的字符串,但前提是它没有用单行注释注释。
我不介意它是否在多行注释中找到字符串(因为除此之外,我认为正则表达式会更加复杂(。
举个例子,假设我想要"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
如果 lookbacks 可以接受不定的 wifth 表达式,你可以在 PHP 中使用 lookback,但实际上你并不真正需要 lookbacks :)前瞻可以做到:
^(?:(?!//).)*?'Kmystring
正则表达式101演示
'K
重置匹配项。
如果你突然想通过说你不希望块注释中的部分来进一步推动这一点,你可以使用更多的前瞻:
^(?:(?!//).)*?'Kmystring(?!(?:(?!/'*)['s'S])*'*/)
正则表达式101演示
或
^(?s)(?:(?!//).)*?'Kmystring(?!(?:(?!/'*).)*'*/)
补遗:
如果您还想在同一行中获取多个mystring
,请将^
替换为(?:'G|^)
'G
在上一场比赛结束时进行比赛。
$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
"
}
}