我知道可以匹配一个单词,然后用其他工具逆转比赛(例如 grep -v)。但是,可以匹配不包含一个特定的单词,例如 hede,使用常规表达式的线条吗?
入口:
hoho
hihi
haha
hede
代码:
grep "<Regex for 'doesn't contain hede'>" input
所需的产量:
hoho
hihi
haha
我知道可以匹配一个单词,然后用其他工具逆转比赛(例如 grep -v)。但是,可以匹配不包含一个特定的单词,例如 hede,使用常规表达式的线条吗?
入口:
hoho
hihi
haha
hede
代码:
grep "<Regex for 'doesn't contain hede'>" input
所需的产量:
hoho
hihi
haha
当前回答
如果你只是用它来捕捉,你可以使用捕捉 -v 以获得所有不包含捕捉的线条。
ETA Oh,重新阅读这个问题,抓 -v 可能是你指的是“工具选项”。
其他回答
下面的功能将帮助您获得所需的产量
<?PHP
function removePrepositions($text){
$propositions=array('/\bfor\b/i','/\bthe\b/i');
if( count($propositions) > 0 ) {
foreach($propositions as $exceptionPhrase) {
$text = preg_replace($exceptionPhrase, '', trim($text));
}
$retval = trim($text);
}
return $retval;
}
?>
我想添加另一个例子,如果你试图匹配一个包含X线的整个线,但也不包含Y线。
这个 regex 模式会工作(在 JavaScript 中也工作)
^(?=.*?tasty-treats)((?!chocolate).)*$
(全球,多线旗在例子中)
互动示例: https://regexr.com/53gv4
比赛
(这些 URL 包含“蛋糕治疗”并且不包含“巧克力”)
example.com/tasty-treats/strawberry-ice-cream example.com/甜点/tasty-treats/banana-pudding example.com/tasty-treats-overview
没有匹配
example.com/tasty-treats/chocolate-cake example.com/home-cooking/over-roasted-chicken example.com/tasty-treats/banana-chocolate-fudge example.com/desserts/chocolate/tasty-treats example.com/chocolate/tasty-treats/desserts
在我看来,一个更可读的答案:
^(?!.*hede)
基本上,“在线的开始,如果和只有如果它没有“<unk>”在它” - 所以要求几乎直接翻译成 reggex。
当然,有可能有多个失败要求:
^(?!.*(hede|hodo|hada))
详细信息: ^ anchor 确保 regex 引擎不会在行中的每个位置撤回比赛,这将匹配每个行。
接口工具匹配每行一次,在与多线条合作的背景下,您可以使用“m”旗帜:
/^(?!.*hede)/m # JavaScript syntax
或
(?m)^(?!.*hede) # Inline flag
不是雷格斯,但我发现使用带管的序列粘贴是合乎逻辑和有用的,以消除噪音。
例如,搜索一个 Apache 配置文件,没有所有评论 -
grep -v '\#' /opt/lampp/etc/httpd.conf # this gives all the non-comment lines
和
grep -v '\#' /opt/lampp/etc/httpd.conf | grep -i dir
序列格雷普的逻辑是(不是一个评论)和(比赛是)
此前提到的(?(?!)*是很棒的,因为它可以被 anchored。
^(?:(?!hede).)*$ # A line without hede
foo(?:(?!hede).)*bar # foo followed by bar, without hede between them
但在这种情况下,以下几点就足够了:
^(?!.*hede) # A line without hede
此简化已准备好添加“和”条款:
^(?!.*hede)(?=.*foo)(?=.*bar) # A line with foo and bar, but without hede
^(?!.*hede)(?=.*foo).*bar # Same