Saturday, December 10, 2022

[FIXED] How to check if a string contain 2 same char in a row?

Issue

I have a regex like this

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

and check password with that regex if it contain 2 same character in a row

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

but I get this error

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

I have read other question that using regexp.MustCompile but I don't know how to handle or code it, is there anyone can help me with the solution?

Here you can check my full code for validate password https://play.golang.com/p/5Fj4-UPvL8s


Solution

You don't need the anchor, the non-capturing group, nor the negative lookahead. Simply match and capture any character ((.)) followed by itself (\\1).

REGEX_2_SAME_CHARACTER_IN_A_ROW = "(.)\\1"

But this brings us to the next problem: Go regexes do not support back references, so you need to find a different solution. One would be looping the string yourself.

Here's a solution with a simple loop:

package main

import (
    "errors"
    "fmt"
    "strings"
)

func main() {
    fmt.Println(ValidatePassword("passsword01"))
}

func ContainsRepeatedChar(s string) bool {
    chars := strings.Split(s, "")
    char := chars[0]
    for i := 1; i < len(chars); i++ {
        if (chars[i] == char) {
            return true
        }
        char = chars[i]
    }
    return false
}

func ValidatePassword(password string) error {
    contain2SameCharacterInARow := ContainsRepeatedChar(password)
    if contain2SameCharacterInARow {
        fmt.Println("duplicated char")
        return errors.New("invalid password")
    }

    fmt.Println("all good")
    return nil
}


Answered By - knittl
Answer Checked By - Pedro (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.