dongshubang7816 2016-06-24 12:30
浏览 50

正则表达式:替换单词,除非后跟破折号

How to replace "cat" in a given string by "FELIX" but not if it's followed by special character like "- or _ or :"

example :

"my cat is hungry all the time" => "my Felix is hungry all the time"

"the products cat-1547 and cat:154 are disponible now" => "the products cat-1547 and cat:154 are disponible now"

thanks

  • 写回答

2条回答 默认 最新

  • droxlzcgnr639823 2016-06-24 12:36
    关注

    Use a negative lookahead together with word boundaries:

    /\bcat\b(?![-:])/
    

    See the regex demo

    Pattern explanation:

    • \b - leading word boundary (to avoid matching cat in tomcat)
    • cat - a literal string cat
    • \b - trailing word boundary (i.e. the next char must be a non-letter, non-digit and non-underscore character, and it prevents from matching cat in catwalk)
    • (?![-:]) - a negative lookahead that fails the match if a - or : immediately follows the cat.

    PHP demo:

    $re = '~\bcat\b(?![-:])~'; 
    $str = "my cat is hungry all the time
    the products cat-1547 and cat:154 are disponible now"; 
    $subst = "Felix"; 
    $result = preg_replace($re, $subst, $str);
    echo $result;
    
    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题