How to Match Any Repeating Character Using Regular Expressions in Go?
In this article, we will address the challenge of matching any character that repeats twice using regular expressions in Go. This task is often straightforward in other regex syntaxes, such as JavaScript, where one can simply use backreference to match repeating characters. However, Go's native regular expression engine (re2) doesn't support backreference.
Can't Use Backreference in Go's re2
The provided JavaScript example leverages backreference to capture repeating characters:
var str = "abccdeff";
var r = /([a-z]{1})\1/g
console.log(str.match(r))
This pattern would fail in Go's re2 due to the lack of backreference support.
Alternatives to Go's re2
To address this limitation, consider these alternatives:
Example Custom Loop Solution
package main
import (
"fmt"
"regexp"
)
func main() {
str := "abccdeff"
// Find and print repeating characters without using regex
for i, ch := range str {
if i 1
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3