简体   繁体   English

正则表达式查找不匹配的多个单词(负单词匹配)

[英]Regex to find multiple words that don't match (Negative words matching)

I need to allow only a specific word per time per string, but exists multiple valid words. 每个字符串每次只允许一个特定的单词,但是存在多个有效单词。

Using the below regex i am not getting the expected result: 使用下面的正则表达式我没有得到预期的结果:

preg_replace('/\b^(true|false|TRUE|FALSE)\b/', '', 'false'); // Returns an empty string, but i expect 'false'

preg_replace('/\b^(true|false|TRUE|FALSE)\b/', '', 'test') // Returns 'test', but i expect an empty string

Someone knows what's wrong? 有人知道怎么了吗?

EDIT 1 编辑1

An example for a long input: 长输入的示例:

preg_replace('/\b^(true|false|TRUE|FALSE)\b/', '', 'This regex allow only boolean, such as true, false, TRUE and FALSE');

It prints: 它打印:

// This regex allow only boolean, such true, false, TRUE and FALSE

But i expect an empty string, because only a sigle word should be a valid match 但是我期望一个空字符串,因为只有一个单词是有效的匹配

Your regex is wrong for what you're trying to do. 您的正则表达式对于您要执行的操作是错误的。 You will need negative lookahead. 您将需要负前瞻。

Try this code: 试试这个代码:

$re = '/\b(?!(?:true|false|TRUE|FALSE))\w+\b/'; 
$str = 'I need true to allow only false specific FALSE words in a TRUE string'; 

$repl = preg_replace($re, "", $str);
//=>   true    false  FALSE    TRUE 

Online Demo 在线演示

Not sure I well understand your needs, but is that OK for you: 不确定我是否完全了解您的需求,但是您是否可以:

if (preg_match('/^(true|false|TRUE|FALSE)$/', $string, $match)) {
    echo "Found : ",$m[1],"\n";
} else {
    echo "Not found\n";
}

In this case you don't need a regex, you can use in_array : 在这种情况下,您不需要正则表达式,可以使用in_array

$arr = array('true', 'false', 'TRUE', 'FALSE');

$result = (in_array($str, $arr, true)) ? $str : '';

Is this what you want? 这是你想要的吗?

(?=.)(true|false|TRUE|FALSE|\\s*)(?!.) (=?)(TRUE | FALSE | TRUE | FALSE | \\ S *)(?!)。

正则表达式可视化

Debuggex Demo Debuggex演示

$regex = '/(?=.)(true|false|TRUE|FALSE|\\s{0,})(?!.)/';
$testString = ''; // Fill this in
preg_match($regex, $testString, $matches);
// the $matches variable contains the list of matches

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

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