Php 正则表达式搜索行不包含另一行前面的字符串
我需要一个正则表达式来查找包含一个字符串的文件行,该字符串前面没有另一个字符串 具体地说,我需要搜索包含“fixed”字符串的行,但它们前面的任何位置都不带“#”。示例:Php 正则表达式搜索行不包含另一行前面的字符串,php,regex,Php,Regex,我需要一个正则表达式来查找包含一个字符串的文件行,该字符串前面没有另一个字符串 具体地说,我需要搜索包含“fixed”字符串的行,但它们前面的任何位置都不带“#”。示例: fixed xxx # fixed yyy aaa # fixed zzz fixed www # bbb Regexp应仅返回以下行: fixed xxx fixed www # bbb 这可以用一个正则表达式完成吗?怎么做 我正在使用PHP 谢谢大家 对不起,我的英语不好。这是您需要的正则表达式(不使用任何查找工具):
fixed xxx
# fixed yyy
aaa # fixed zzz
fixed www # bbb
Regexp应仅返回以下行:
fixed xxx
fixed www # bbb
这可以用一个正则表达式完成吗?怎么做
我正在使用PHP
谢谢大家
对不起,我的英语不好。这是您需要的正则表达式(不使用任何查找工具): 说明:
^ - 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的建议。因为比较都是按行进行的,所以我会尝试这样的方法 (伪代码)
或者是消极的回头看方式:
(?<!#\s)fixed.*
使用正则表达式负查找:
这种方法从行尾检查到行首。
如果
fixed#fixed
# '/^(?!.*\#.*fixed).*fixed.*/m'
^
(?! .* \# .* fixed )
.*
fixed
.*
Regex Negative LookbehindIf
fixed
应始终位于行的开头,您可以使用常规字符串函数(基于示例)。可能希望使[^#]
->[^#\n]
不跨行。这实际上是/m修饰符的工作/m仅处理^$。正则表达式匹配“here is\nffixed\#”
:设置此修饰符时,“行的开始”和“行的结束”构造分别匹配主题字符串中任何换行之后或之前,以及解析为与跨行无关的起始和结束处。您的正则表达式与“\n\n\n\nhere\n\n\nis\n\n\n\n\n\n正则表达式\n\n\n正则表达式\n\n\n\n已修复\ \已修复”
尝试一下<代码>[^#]也匹配换行符、cr和任何换行符。
(?<!#\s)fixed.*
$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
)
)
$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.*/m'
^
(?! .* \# .* fixed )
.*
fixed
.*