正则表达式搜索行不包含前面的字符串



我需要一个正则表达式来查找包含前面没有另一个字符串的文件行。

具体来说,我需要搜索包含"固定"字符串的行,但它们在任何先前位置都没有"#"前面。例子:

fixed xxx
# fixed yyy
aaa # fixed zzz
fixed www # bbb

正则表达式应仅返回以下行:

fixed xxx
fixed www # bbb

这可以用单个正则表达式完成吗?如何?

我正在使用PHP。

谢谢大家。

PD:对不起我的英语。

这是

你需要的正则表达式(不使用任何环视):

/^[^#n]*fixed[^n]*$/m

解释:

^ - beginning of a line
[^#n]* - any amount of chars that are not "#" and are not line breaks
fixed - the string itself
[^n]* - any other characters that are not line breaks
$ - until the end of a line
/m - multiline modifier: http://php.net/manual/ro/reference.pcre.pattern.modifiers.php

在 PHP 中:

$lines = "fixed xxxn# fixed yyynaaa # fixed zzznfixed www # bbb";
$matches = array();
preg_match_all('/^[^#]*fixed.*$/m', $lines, $matches);
var_dump($matches);

结果:

array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(9) "fixed xxx"
    [1]=>
    string(15) "fixed www # bbb"
  }
}

感谢@sln的建议。

由于比较都是按行进行的,我会尝试这样的事情......

(伪代码)

Regex regex = new Regex("^[0-9]"); //a string that starts with a number
string thisLine = input.getLine();
while(hasInput)
{
   string lastLine = thisLine;
   string thisLine = input.getLine();
   if(regex.hasMatch(lastLine)) 
   {
       System.out.println(thisLine)
   }
}

使用正则表达式负面回溯:现场演示

$reg = '/(?<!#s)(fixed.+)/';
$input = '
fixed xxx
# fixed yyy
aaa # fixed zzz
fixed www # bbb';
preg_match_all($reg, $input, $output);
$output = $output[0];
print_r($output);

输出:

Array
(
    [0] => fixed xxx
    [1] => fixed www # bbb
)

此方法从行尾到开头进行检查。
fixed # fixed的情况下

 #  '/^(?!.*#.*fixed).*fixed.*/m'
 ^ 
 (?! .* # .* fixed )
 .* 
 fixed
 .* 

或者消极的背后看法:

(?<!#s)fixed.*

例:

http://regex101.com/r/rR4eG1

.PHP:

$string = "fixed xxx
# fixed yyy
aaa # fixed zzz
fixed www # bbb";
preg_match_all("/(?<!#s)fixed.*/", $string, $matches);
print_r($matches);

输出:

Array
(
    [0] => Array
        (
            [0] => fixed xxx
            [1] => fixed www # bbb
        )
)

最新更新