2017-01-08 39 views
3

这里是我的字符串:如果它不包含特定单词,我该如何匹配它?

$str = "this is a string 
     this is a test string"; 

我想匹配的一切this与字之间string(加上本身)

注意:这两个词之间可以是除了test之外的所有词。

所以我试图匹配this is a string,但不是this is a test string。因为第二个包含test这个词。


这是我目前的格局:

/this[^test]+string/gm 

But it doesn't work as expected

我怎样才能解决呢?

+0

我没有得到'test'部分。请你解释一下 – mrid

+0

@mrid我想匹配每个以'this'开头并以'string'结尾的句子,如果该句子不包含'test'的话。 – Shafizadeh

+0

@mrid反之亦然https://regex101.com/r/ENHYLD/3 – Shafizadeh

回答

2

你做的事情是这样被排除在列表中的“测试”的任何字符。做到这一点的方法是使用negative lookarounds。正则表达式然后看起来像这样。

this((?!test).)*string

+0

你需要通过添加'?'来使其变成'lazy',就像这样(this?(?!test)。)*?string'。测试你的正则表达式以下'这是一个字符串这是一个字符串这是一个字符串这是一个字符串这是一个字符串' – developer

-1

如果你想做到这一点没有正则表达式,你可以使用fnmatch()

function match($str) 
{ 
    if (strpos($str, 'test') == false) /* doesn't contain test */ 
    { 
     if (fnmatch('this*string', $str)) 
     { 
      return true; 
     } 
     else 
     { 
      return false; 
     } 
    } 
    else 
     return false; 
} 
+0

可以解释downvote? – mrid

相关问题