英文:
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)
}
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论