2 回答

TA貢獻1877條經驗 獲得超6個贊
環顧四周后,我認為@tshiono的想法是最有意義的,但正則表達式與我的期望不符。我最終得到了這樣的東西
package main
import (
"fmt"
"regexp"
)
func main() {
st := []string{
"test-adccount",
"s-asdgaysdtuaystdua",
"2342348jtdstyfu",
"kdshkjfshdkfjhd-jkshdfjkshdf",
"uysiufysdusidyf-jsdkhfjksdhf",
"ausyduaysidyaisyd",
"2abc-f",
"d-23423423",
"-iasodaisdyauiysd",
"sudyfisdufy82|ldjf",
"klskdjfsd898883---sdfkjskdfjsld",
}
for _, s := range st {
r1 := regexp.MustCompile(`^([\da-zA-Z]+)([\da-zA-Z-]+)$`)
r2 := regexp.MustCompile(`^(d-).+$`)
if r1.MatchString(s) && !r2.MatchString(s) {
fmt.Println(fmt.Sprintf("%s :: matched", s))
} else {
fmt.Println(fmt.Sprintf("%s :: does not matched", s))
}
}
}
https://play.golang.org/p/j-7INwyDwU4

TA貢獻1798條經驗 獲得超7個贊
正向查找斷言可以在不使用的情況下更改,但否定查找不能。我們需要將正則表達式拆分為兩個步驟邏輯。
例如,我們可以在中說以下內容:PCREpython
import re
s = '2abc-D' # matches
#s = 'd-D' # doesn't match
m = re.match(r'^(?!d-)([\da-zA-Z]+)(-[\da-zA-Z])$', s)
if (m):
print(m.groups())
在 中,我們需要說:Golang
package main
import (
"fmt"
"regexp"
)
func main() {
s := "2abc-D" // matches
// s := "d-D" // doesn't match
r := regexp.MustCompile(`^([\da-zA-Z]+)(-[\da-zA-Z])$`)
if !(regexp.MustCompile(`^d-`).MatchString(s)) {
fmt.Println(r.FindStringSubmatch(s))
}
}
- 2 回答
- 0 關注
- 162 瀏覽
添加回答
舉報