【golang】error parsing regexp: invalid or unsupported Perl syntax (正则表达式校验密码)

要在 Go 中编写密码校验规则,确保密码不少于8位且包含数字和字母,你可以使用正则表达式和 Go 的 regexp 包来实现。以下是一个示例代码:

错误示范

package main

import (
    "fmt"
    "regexp"
)

func validatePassword(password string) bool {
    // 定义正则表达式,要求密码至少包含一个数字和一个字母,并且至少8位长度
    regexPattern := "^(?=.*[0-9])(?=.*[a-zA-Z]).{8,}$"
    regex := regexp.MustCompile(regexPattern)

    // 使用正则表达式进行匹配
    return regex.MatchString(password)
}

func main() {
    password1 := "Password123" // 合法密码,包含数字和字母,长度大于等于8
    password2 := "abc123"      // 不合法密码,长度不足8
    password3 := "abcdefg"     // 不合法密码,没有数字
    password4 := "12345678"    // 不合法密码,没有字母

    fmt.Printf("Password1: %v\n", validatePassword(password1))
    fmt.Printf("Password2: %v\n", validatePassword(password2))
    fmt.Printf("Password3: %v\n", validatePassword(password3))
    fmt.Printf("Password4: %v\n", validatePassword(password4))
}

在这个示例中,validatePassword 函数接受一个密码字符串作为参数,并使用正则表达式来检查密码是否满足要求。正则表达式 ^(?=.*[0-9])(?=.*[a-zA-Z]).{8,}$ 要求密码至少包含一个数字和一个字母,并且长度至少为8位。

你可以根据需要调用 validatePassword 函数来验证用户输入的密码是否符合规则。上面的示例在 main 函数中演示了如何使用它来验证不同的密码。

报错信息

panic: regexp: Compile(^(?=.*[0-9])(?=.*[a-zA-Z]).{8,}$): error parsing regexp: invalid or unsupported Perl syntax: (?=

原因

regexp 不支持的Perl语法, 可以改用github.com/dlclark/regexp2

正确代码

package main

import (
	"Test/Module"
	"fmt"
	"github.com/dlclark/regexp2"
	"regexp"
	"time"
)

func validatePassword(password string) bool {
	// 定义正则表达式,要求密码至少包含一个数字和一个字母,并且至少8位长度
	regexPattern := "^(?=.*[0-9])(?=.*[a-zA-Z]).{8,}$"
	regex := regexp.MustCompile(regexPattern)

	// 使用正则表达式进行匹配
	return regex.MatchString(password)
}

func regexpMatch(matchStr string) bool {
	regexPattern := "^(?=.*[0-9])(?=.*[a-zA-Z]).{8,}$"
	reg, _ := regexp2.Compile(regexPattern, 0)
	m, err := reg.FindStringMatch(matchStr)
	if err != nil {
		return false
	}
	return m != nil
}

func main() {
    password1 := "Password123" // 合法密码,包含数字和字母,长度大于等于8
    password2 := "abc123"      // 不合法密码,长度不足8
    password3 := "abcdefg"     // 不合法密码,没有数字
    password4 := "12345678"    // 不合法密码,没有字母

    fmt.Printf("Password1: %v\n", regexpMatch(password1))
    fmt.Printf("Password2: %v\n", regexpMatch(password2))
    fmt.Printf("Password3: %v\n", regexpMatch(password3))
    fmt.Printf("Password4: %v\n", regexpMatch(password4))
}

输出

Password1: true
Password2: false
Password3: false
Password4: false

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值