您可以使用这两种方法之一。
你可以匹配所有以
//
跳过它们,只匹配其他上下文中的子字符串。
'~^(\s*//.*)(*SKIP)(*F)|^(?:\s*Connection\s+)?(.+?)\s*=\s*new\s+DBConnection~m'
见
regex demo
PHP demo
:
$re = '~^(\s*//.*)(*SKIP)(*F)|^(?:\s*Connection\s+)?(.+?)\s*=\s*new\s+DBConnection~m';
$str = "Connection variable = new DBConnection\n variable = new DBConnection\n //\n //Connection variable = new DBConnection\n //variable = new DBConnection\n // Connection variable = new DBConnection\n // variable = new DBConnection";
if (preg_match_all($re, $str, $matches)) {
print_r($matches[0]);
}
输出:
Array
(
[0] => Connection variable = new DBConnection
[1] => variable = new DBConnection
)
方法2:可选的捕获组和一些后处理
在php pcre regex模式中,不能使用无限宽lookbehinds,这意味着不能用
*
,
+
,
*?
,
+?
,
?
,
?
,
{1,4}
,
{3,}
量词。此外,也不能使用嵌套交替。
通常的解决方法是使用
可选捕获组
并在找到匹配项后检查其值。如果组值不为空,则表示匹配应为“失败”,丢弃,否则,获取所需的捕获。
下面是一个正则表达式示例:
'~^(\s*//)?(?:\s*Connection\s+)?(.+?)\s*=\s*new\s+DBConnection~m'
见
regex demo
:
绿色突出显示的子字符串是组1匹配项。我们可以这样在代码中检查它们:
$result = ""; // Result is empty
if (preg_match($rx, $s, $m)) { // Is there a match?
if (empty($m[1])) { // Is the match group #1 empty?
$result = $m[0]; // If yes, we found a result
}
} // Else, result will stay empty
见
PHP demo
:
$strs = ['Connection variable = new DBConnection', 'variable = new DBConnection', '//Connection variable = new DBConnection', '//variable = new DBConnection'];
$rx = '~^(\s*//)?(?:\s*Connection\s+)?(.+?)\s*=\s*new\s+DBConnection~m';
foreach ($strs as $s) {
echo "$s:\n";
if (preg_match($rx, $s, $m)) {
if (empty($m[1])) {
echo "FOUND:" . $m[0] . "\n--------------\n";
}
} else {
echo "NOT FOUND\n--------------\n";
}
}
输出:
Connection variable = new DBConnection:
FOUND:Connection variable = new DBConnection
--------------
variable = new DBConnection:
FOUND:variable = new DBConnection
--------------
//Connection variable = new DBConnection:
//variable = new DBConnection:
同样的技术也可以用于
preg_replace_callback
如果你需要更换。