匹配一个字符串后面跟着另一个字符串(preg_match负向前看)

时间:2012-07-05 15:43:41

标签: php preg-match

我必须选择包含单词one而不是another的行。这些行形成一些json字符串,如:

{"Name" : "one", "LastError" : "No error", "ID" : 1000 , "Comment" : "no comment"} //YES
{"Name" : "one", "LastError" : "No error", "ID" : 1000 , "Comment" : "another"} //NO because there is 'one' and 'another'

我正在使用php和preg_match。

我试图使用像:

if (preg_match('/one.*(?!another)/i',$row_string) > 0)
{
  //no draw
}
else
{
  //Draw something
}

看起来前瞻没有做任何事情。

2 个答案:

答案 0 :(得分:7)

你的正则表达式

/one.*(?!another)/

表示匹配字符串one后跟任意数量的字符,.*后的字符串不得与another 匹配。

.*基本上会匹配字符串的结尾,因此another后面没有。

您真正想要的是匹配字符串one后跟任意数量的字符,并且每个字符都不能跟another

这个有效:

/one(.(?!another))*$/

$确保针对one之后的每个字符测试断言。

为了确保即使one本身不在another之前,我们也必须在one之后添加断言:

/one(?!another)(.(?!another))*$/

答案 1 :(得分:0)

one仅在Name?如果是,json_decode($json, true)