gpt4 book ai didi

regex - 如何转换使用 Lookahead 的正则表达式模式?

转载 作者:IT王子 更新时间:2023-10-29 02:30:49 25 4
gpt4 key购买 nike

我无法将此正则表达式转换为 Golang 支持的内容。我能得到一些帮助吗?它最初来自 this SO question .

^(?=.{1,24}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$

标准如下:

  1. Only contains alphanumeric characters, underscore and dot.
  2. Underscore and dot can't be at the end or start of a username (e.g _username / username_ / .username / username.).
  3. Underscore and dot can't be next to each other (e.g user_.name).
  4. Underscore or dot can't be used multiple times in a row (e.g user__name / user..name).

最佳答案

我没有任何使用 Go 的经验,所以也许有人可以想出更好的解决方案。
这是我找到的两个选项:

1。编写一个涵盖所有内容的正则表达式除了长度限制

你可以这样使用:

^(?:[a-zA-Z0-9]+[._]?[a-zA-Z0-9]+)+$

Regex101 demo .

你可以使用 len检查字符串长度。这是一个完整的例子:

func main() { 
var re = regexp.MustCompile(`(?m)^(?:[a-zA-Z0-9]+[._]?[a-zA-Z0-9]+)+$`)
var str = `username
user_name
user.name
user.name_123
username$$$
_username
username_
user_.name
user._name
user__name
user..name
VeryLongUserNameThatExceedsTheLimit
`
for i, match := range re.FindAllString(str, -1) {
if len(match) <= 24 {fmt.Println(match, "found at index", i)}
}
}

输出:

username found at index 0
user_name found at index 1
user.name found at index 2
user.name_123 found at index 3

Test it online .


2。使用第三方引擎

我找到了 this .NET-based engine应该支持 Lookarounds。如果以前的解决方案不适合你,你可以看看这个。请注意,该引擎的作者建议尽可能使用内置引擎:

You'll likely be better off with the RE2 engine from the regexp package and should only use this if you need to write very complex patterns or require compatibility with .NET.

关于regex - 如何转换使用 Lookahead 的正则表达式模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55507089/

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