douji1853 2016-06-23 07:23
浏览 111
已采纳

需要regexp条件

It is necessary to check string. It should contain one substring AND dont contain other substring. This should works only with regexp.

Examples. We accept string with 'fruit' substring, but don't accept string contains substring 'love':

We all love green fruit. -> dont match
We all love to walk. -> dont match
We all green fruit. -> match

Write one regex if it possible.

/(?<!love).+fruit/ dont work
  • 写回答

2条回答 默认 最新

  • duanmeng1858 2016-06-23 07:28
    关注

    Surely, you can achieve what you want with strpos, but you specified you only need a regex solution. Note that this is not the best approach for this task unless you need to check for the substrings in a specific context (like within word boundaries, or after or before specific symbols, etc.)

    The (?<!love).+fruit regex matches any 1+ characters that are not preceded with love substring up to the fruit substring. It will match I love fruit because the lookbehind asserts true at the beginning of the string, then .+ grabs the whole string, then backtracking does its job to get fruit.

    In fact, you only need 1 lookahead to check if there is no love anchored at the start of the string:

    ^(?!.*love).*fruit
     ^^^^^^^^^^
    

    See the regex demo

    You only check for the substring love with (?!.*love) at the beginning of the string (due to ^), and then, if it is missing, the regex goes on matching any characters (other than a newline if /s modifier is not use) up to the last fruit.

    Here is a PHP demo:

    $re = "/^(?!.*love).*fruit/"; 
    if (preg_match($re, "We all love green fruit."))
    { 
       echo "Matched!";  // Won't be displayed since there is no match
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真