前瞻正则表达式 – 识别重复的连续字母

huangapple go评论90阅读模式
英文:

Lookahead regular expression - Identify duplicate consecutive letters

问题

我有一个字符串,例如 "Hello Worrld"。注意到字母 "r" 重复了两次。

我希望能够识别连续出现(两次或更多)的字母,并只保留其中一个。也就是说,我希望得到 "Hello World",只保留一个 "r"。

Golang 似乎没有前瞻正则表达式。

我尝试使用以下正则表达式来识别连续重复的字母:

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

但它选择了两个字母的所有出现 - 我只希望选择其中一个。

英文:

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(`(.)`)

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

答案1

得分: 5

你可以使用pcre绑定,但如果你只想删除重复的字母,你可以使用strings.Map函数。例如:

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

英文:

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

<kbd>playground</kbd>

huangapple
  • 本文由 发表于 2015年2月22日 13:28:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/28654876.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定