gpt4 book ai didi

regex - 用于密码检查的 PHP 正则表达式模式在 Go 中不起作用

转载 作者:IT王子 更新时间:2023-10-29 01:58:41 25 4
gpt4 key购买 nike

看完this post ,我知道我需要使用反引号 (`) 来包装我的正则表达式模式。现在我有正则表达式模式 /^(?=^.{8,}$)(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?! .*\s)[0-9a-zA-Z!@#$%^&*()]*$/ 检查密码模式是否正确。我已经用 PHP 对其进行了测试,它可以正常工作。但它在 Go 中不起作用。为什么?

顺便问一下,反引号 ( ` ) 变量的类型是什么?好像不是string类型。如何声明这个变量容器?

测试代码

package main

import(
"fmt"
"regexp"
)

func main(){
re := regexp.MustCompile(`/^(?=^.{8,}$)(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s)[0-9a-zA-Z!@#$%^&*()]*$/`)
fmt.Println(re.MatchString("aSfd46Fgwaq"))
}

测试结果

Running...

panic: regexp: Compile(`/^(?=^.{8,}$)(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s)[0-9a-zA-Z!@#$%^&*()]*$/`): error parsing regexp: invalid or unsupported Perl syntax: `(?=`

goroutine 1 [running]:
panic(0x4efae0, 0xc82000a340)
/usr/local/go/src/runtime/panic.go:481 +0x3e6
regexp.MustCompile(0x576140, 0x4b, 0x100000000)
/usr/local/go/src/regexp/regexp.go:232 +0x16f
main.main()
/home/casper/.local/share/data/liteide/goplay.go:9 +0x30
exit status 2

Error: process exited with code 1.

谢谢!

最佳答案

Go 正则表达式不支持环视。此外,也不支持 /.../ 正则表达式定界符(Go 中有特殊方法来表达这些定界符)。

您可以为 Go 使用支持环视的正则表达式库 (here is a PCRE-supporting one) 或拆分条件并使用几个小的、可读的正则表达式:

package main

import (
"fmt"
"regexp"
"unicode/utf8"
)

func main() {
s := "aSfd46Fgwaq"
lower_cond := regexp.MustCompile(`[a-z]`)
upper_cond := regexp.MustCompile(`[A-Z]`)
digit_cond := regexp.MustCompile(`[0-9]`)
whole_cond := regexp.MustCompile(`^[0-9a-zA-Z!@#$%^&*()]*$`)
pass_len := utf8.RuneCountInString(s)
fmt.Println(lower_cond.MatchString(s) && upper_cond.MatchString(s) && digit_cond.MatchString(s) && whole_cond.MatchString(s) && pass_len >= 8)
}

参见 Go playground demo

注意:我在演示中使用了 utf8.RuneCountInString 以确保即使是 UTF8 字符串长度也能被正确解析。否则,您可以使用 len(s) 来计算足以满足 ASCII 输入的字节数。

更新

如果性能不理想,可以考虑使用更简单的非regex方式:

package main

import "fmt"

func main() {
myString := "aSfd46Fgwaq"
has_digit := false
has_upper := false
has_lower := false
pass_length := len(myString)
for _, value := range myString {
switch {
case value >= '0' && value <= '9':
has_digit = true
case value >= 'A' && value <= 'Z':
has_upper = true
case value >= 'a' && value <= 'z':
has_lower = true
}
}
fmt.Println(has_digit && has_upper && has_lower && pass_length >= 8)

}

参见 another Go demo

关于regex - 用于密码检查的 PHP 正则表达式模式在 Go 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38543687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com