如何检查一个字符串是否连续包含 2 个相同的字符?

我有这样的正则表达式

REGEX_2_SAME_CHARACTER_IN_A_ROW = "^(?:(.)(?!\\1\\1))*$"

并使用该正则表达式检查密码是否连续包含 2 个相同的字符

contain2SameCharacterInARow, err := regexp.MatchString(REGEX_2_SAME_CHARACTER_IN_A_ROW, password)

但我得到这个错误

error match regex 2 same char in a row: error parsing regexp: invalid or unsupported Perl syntax: `(?!`

我读过其他使用 regexp.MustCompile 的问题,但我不知道如何处理或编码,有没有人可以帮助我解决这个问题?

在这里您可以查看我的完整代码以验证密码 https://play.golang.com/p/5Fj4-UPvL8s


慕标5832272
浏览 109回答 1
1回答

暮色呼如

您不需要锚点、非捕获组或负面前瞻。只需匹配并捕获任何字符 (&nbsp;(.)) 后跟自身 (&nbsp;\\1)。REGEX_2_SAME_CHARACTER_IN_A_ROW&nbsp;=&nbsp;"(.)\\1"但这给我们带来了下一个问题:Go regexes do not support back references,所以你需要找到一个不同的解决方案。一个是自己循环字符串。这是一个简单循环的解决方案:package mainimport (&nbsp; &nbsp; "errors"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "strings")func main() {&nbsp; &nbsp; fmt.Println(ValidatePassword("passsword01"))}func ContainsRepeatedChar(s string) bool {&nbsp; &nbsp; chars := strings.Split(s, "")&nbsp; &nbsp; char := chars[0]&nbsp; &nbsp; for i := 1; i < len(chars); i++ {&nbsp; &nbsp; &nbsp; &nbsp; if (chars[i] == char) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; char = chars[i]&nbsp; &nbsp; }&nbsp; &nbsp; return false}func ValidatePassword(password string) error {&nbsp; &nbsp; contain2SameCharacterInARow := ContainsRepeatedChar(password)&nbsp; &nbsp; if contain2SameCharacterInARow {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("duplicated char")&nbsp; &nbsp; &nbsp; &nbsp; return errors.New("invalid password")&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println("all good")&nbsp; &nbsp; return nil}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go