负向后看 [英] Negative lookbehind alternative

查看:50
本文介绍了负向后看的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串

百年纪念日

我只想在 cen 之前不匹配 ten .

到目前为止,我有这个正则表达式:

So far I have this regex:

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

在以下情况下返回 true :十进制, blahtenary 和false(对于 centary cetenary)百年纪念

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)
}

推荐答案

由于缺少对前行或后行的支持,我们需要坚持使用否定的字符类-但 [^ c] [^ e] [^ n] 不能完全覆盖它,因为它不允许cxxten,也不能覆盖 ten 前没有3个字符的字符串.

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.

我想出了(?:^ | [^ n] |(?:[^ e] | ^)n |(?:[^ c] | ^)en)ten ,将存储到第一个捕获的组中.它正在为每种可能的方法创建与 cen 不完全匹配的替代方法.

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.

另一种选择可能是匹配(.{0,3})(ten),如果第一组存储了 cen ,则以编程方式放弃该匹配.

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

这篇关于负向后看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆