简体   繁体   English

regex:除这些单词外,如何匹配这些单词?

[英]regex: How to match these words except those words?

I want to match some words in regex except some others: 除了其他一些词,我想匹配正则表达式中的一些词:

ex: all words that contains straat, laan, baan 例如:所有包含straat,laan,baan的单词

(straat|laan|baan)

But not 但不是

(overslaan|bestraat|rubaan)

ex: mystraat bolaan overslaan boobaan rubaan 例如:mystraat bolaan overslaan boobaan rubaan

should match 应该匹配

mystraat bolaan boobaan mystraat bolaan boobaan

That's a bit complex but can be done with a negative lookbehind. 这有点复杂,但是可以通过消极的掩饰来完成。

Try something like this: 尝试这样的事情:

$goodString = "coolbaan";
$badString = "rubaan";

$stringToTest = $goodString;

$regexPattern = '/(.*?)((?<!overs|ru|be)(straat|laan|baan))/';

preg_match($regexPattern, $stringToTest, $matches);
if ($matches) {
  // $matches[1] will be the prefix - e.g. ru
  // $matches[2] will be the suffix e.g. baan
  // $result will be 'rubaan'
  $result = "{$matches[1]}{$matches[2]}";
} else {
  $result = 'No Match!';
}
echo $result;

只需在正则表达式和$之前添加^,以结束下面的代码:

/^[straat|laan|baan]$/

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

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