1 回答
TA貢獻1775條經驗 獲得超11個贊
在基于 Go RE2 的正則表達式中,您不能使用環視,因此只能使用另一個正則表達式或常規字符串長度檢查來檢查長度限制。
完全非正則表達式的方法(演示):
package main
import (
"fmt"
"strings"
)
func IsAlnumOrHyphen(s string) bool {
for _, r := range s {
if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') && (r < '0' || r > '9') && r != '-' {
return false
}
}
return true
}
func main() {
s := "abc-abc-abc"
if len(s) < 40 && len(s) > 0 && !strings.HasPrefix(s, "-") && !strings.Contains(s, "--") && !strings.HasSuffix(s, "-") && IsAlnumOrHyphen(s) {
fmt.Println("true")
} else {
fmt.Println("false")
}
}
細節
len(s) < 40 && len(s) > 0- 長度限制,允許 1 到 39 個字符!strings.HasPrefix(s, "-")- 不應以-!strings.Contains(s, "--")- 不應包含--!strings.HasSuffix(s, "-")- 不應以以下結尾-IsAlnumOrHyphen(s)- 只能包含 ASCII 字母數字和連字符。
對于部分正則表達式方法,請參閱此 Go 演示:
package main
import (
"fmt"
"regexp"
)
func main() {
usernameConvention := "^[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*$"
re,_ := regexp.Compile(usernameConvention)
s := "abc-abc-abc"
if len(s) < 40 && len(s) > 0 && re.MatchString(s) {
fmt.Println("true")
} else {
fmt.Println("false")
}
}
在這里,^[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*$正則表達式匹配
^- 字符串的開頭[a-zA-Z0-9]+- 1 個或多個 ASCII 字母數字字符(?:-[a-zA-Z0-9]+)*- 0 次或多次重復-,然后是 1 次或更多 ASCII 字母數字字符$- 字符串末尾。
- 1 回答
- 0 關注
- 281 瀏覽
添加回答
舉報
