如何在Go中模拟负向后看 [英] How to simulate negative lookbehind in Go

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

问题描述

我正在尝试编写一个可提取命令的正则表达式,这是到目前为止我使用负向后置断言得出的结论:

I'm trying to write a regex that can extract a command, here's what I've got so far using a negative lookbehind assertion:

\b(?<![@#\/])\w.*

输入以下内容:

/msg @nickname #channel foo bar baz
/foo #channel @nickname foo bar baz 
foo bar baz

每次提取

foo bar baz.参见工作示例 https://regex101.com/r/lF9aG7/3

foo bar baz is extracted every time. See working example https://regex101.com/r/lF9aG7/3

但是在Go中,它不能编译 http://play.golang.org/p/gkkVZgScS_

In Go however this doesn't compile http://play.golang.org/p/gkkVZgScS_

它抛出:

panic: regexp: Compile(`\b(?<![@#\/])\w.*`): error parsing regexp: invalid or unsupported Perl syntax: `(?<`

我做了一些研究,发现该语言不支持负向回溯以保证O(n)时间.

I did a bit of research and realized negative lookbehinds are not supported in the language to guarantee O(n) time.

我该如何重写此正则表达式,使其在不产生负面效果的情况下也能正常运行?

How can I rewrite this regex so that it does the same without negative lookbehind?

推荐答案

由于在后面具有否定性,因此您仅使用简单的字符集;您可以将其替换为否定的字符集:

Since in your negated lookbehind, you are only using a simple character set; you can replace it with a negated character-set:

\b[^@#/]\w.*

如果在字符串的开头允许使用,则使用^锚点:

If the are allowed at the start of the string, then use the ^ anchor:

(?:^|[^@#\/])\b\w.*


根据您问题中转到游乐场"的示例,我认为您正在寻找过滤所有以[#@/]中的字符开头的单词的方法.您可以使用filter函数:


Based on the samples in Go playground link in your question, I think you're looking to filter out all words beginning with a character from [#@/]. You can use a filter function:

func Filter(vs []string, f func(string) bool) []string {
    vsf := make([]string, 0)
    for _, v := range vs {
        if f(v) {
            vsf = append(vsf, v)
        }
    }
    return vsf
}

Process函数,该函数利用了上面的过滤器:

and a Process function, which makes use of the filter above:

func Process(inp string) string {
    t := strings.Split(inp, " ")
    t = Filter(t, func(x string) bool {
        return strings.Index(x, "#") != 0 &&
            strings.Index(x, "@") != 0 &&
            strings.Index(x, "/") != 0
    })
    return strings.Join(t, " ")
}

可以在游乐场上看到它的运行情况play.golang.org/p/ntJRNxJTxo"rel =" nofollow> http://play.golang.org/p/ntJRNxJTxo

It can be seen in action on playground at http://play.golang.org/p/ntJRNxJTxo

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

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