Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lookahead regular expression - Identify duplicate consecutive letters

Tags:

regex

go

I have a string - for example, "Hello Worrld". Notice the "r" letter repeats twice.

I wish to identify letters that occur consecutively (two or more times) and retain only one of them. That is, I wish to get "Hello World" with a single "r".

Golang does not seem to have lookahead regular expression.

I tried using the following regular expression to identify letters that repeat consecutively -

r := regexp.Compile(`(.)\1`)

But it selects both the occurrences of the letters - I would want only one of them to be selected.

like image 522
callmekatootie Avatar asked Feb 22 '15 05:02

callmekatootie


1 Answers

You could use pcre bindings, however if you just want to remove dup letters you could use strings.Map, for example:

func stripDups(s string) string {
    var last rune
    return strings.Map(func(r rune) rune {
        if r != last {
            last = r
            return r
        }
        return -1
    }, s)
}

playground

like image 55
OneOfOne Avatar answered Oct 11 '22 07:10

OneOfOne