dongzanghong4379 2016-06-24 13:15
浏览 11
已采纳

负向后看

I have a string

centenary

I'd like to match ten only when it is not preceded by cen.

So far I have this regex:

(([^c][^e][^n])|^)ten

That returns true in the following cases tenary, blahtenary and false for ctenary, cetenary, centanary

package main

import (
    "fmt"
    "regexp"
)

func main() {
    txt := "ctenary"
    rx := `(([^c][^e][^n])|^)ten`
    re := regexp.MustCompile(rx)
    m := re.MatchString(txt)
    fmt.Println(m)
}
  • 写回答

1条回答 默认 最新

  • dpbyr64224 2016-06-24 13:41
    关注

    Due to the missing support for either lookahead or lookbehind, we need to stick to negated character classes - but [^c][^e][^n] doesn't fully cover it, as it would not allow cxxten and also not cover strings where there aren't 3 characters before ten.

    I came up with (?:^|[^n]|(?:[^e]|^)n|(?:[^c]|^)en)ten, that stores ten into the first captured group. It's creating alternatives for each possible way to not exactly match cen.

    An alternative might be matching (.{0,3})(ten) and discard the match programatically if the first group stores cen.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测