正则表达式搜索行不包含另一个字符串

时间:2014-01-16 17:50:16

标签: php regex

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

具体来说,我需要搜索包含“固定”字符串的行,但在之前的任何位置都不会出现“#”。例子:

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

Regexp应仅返回以下行:

fixed xxx
fixed www # bbb

这可以用一个正则表达式完成吗?怎么样?

我正在使用PHP。

谢谢大家。

PD:抱歉我的英文。

5 个答案:

答案 0 :(得分:3)

这是你需要的正则表达式(不使用任何外观):

/^[^#\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 xxx\n# fixed yyy\naaa # fixed zzz\nfixed 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获取建议。

答案 1 :(得分:0)

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

(伪代码)

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)
   }
}

答案 2 :(得分:0)

或负面的背后方式:

(?<!#\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
        )
)

答案 3 :(得分:0)

使用Regex Negative Lookbehind:Live Demo

$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
)

答案 4 :(得分:0)

这种方法从行尾回到开始检查 加入fixed # fixed

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

 ^ 
 (?! .* \# .* fixed )
 .* 
 fixed
 .* 
相关问题