dqcd84732 2012-07-05 15:43
浏览 99
已采纳

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

I have to select rows that contain the word one and not another. The rows come form some json string, like those:

{"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'

I am using php and preg_match.

I'am trying to use someting like:

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

It seems that the look ahead doesn't do anything.

  • 写回答

2条回答 默认 最新

  • duan1989643 2012-07-05 16:14
    关注

    Your regex

    /one.*(?!another)/
    

    means match the string one followed by any number of characters, and the string after .* must not match another.

    .* will basically match up to the end of the string, so it isn't followed by another.

    What you actually want is to match the string one followed by any number of characters, and each of them must not be followed by another.

    This one works:

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

    The $ makes sure that the assertion is tested against every character following one.

    To make sure that even one itself isn't preceded by another, we have to add the assertion just after one too:

    /one(?!another)(.(?!another))*$/
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)