简体   繁体   English

使用正则表达式匹配特定模式

[英]Using regex to match a specific pattern

I'm trying to match any strings that doesn't start with "false1" or "false2", and ends with true, but the regex isn't matching for some reason. 我正在尝试匹配所有不以“ false1”或“ false2”开头且以true结尾的字符串,但是正则表达式由于某些原因不匹配。 What am I doing wrong? 我究竟做错了什么?

$text = "start true";
$regex = "~(?:(^false1|false2).+?) true~";
if (preg_match($regex, $text, $match)) {

echo "true";    

}

Expected Result: 预期结果:

true

Actual Result: 实际结果:

null

You may use negative lookahead. 您可以使用负前瞻。

^(?!false[12]).*true$

If you really want to use boundaries then try this, 如果您真的想使用边界,请尝试一下,

^(?!false[12]\b).*\btrue$

DEMO DEMO

Update: 更新:

^(?!.*false[12]\b).*\btrue$

(?!.*false[12]\\b) negative lookahead which asserts that the string would contain any char but not the sub-string false1 or false2 and it must ends with the string true , that's why we added true$ at the last. (?!.*false[12]\\b)它断言,该字符串包含任何字符,但不是子串负先行false1false2 ,它必须以字符串结尾true ,这就是为什么我们增加了true$在最后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM