亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

匹配 begging 和 end 字符而不從另一個搜索中獲取它們

匹配 begging 和 end 字符而不從另一個搜索中獲取它們

Go
呼喚遠方 2022-06-13 15:26:44
如果不使用正則表達式環顧四周(go 不支持),我如何匹配開始和結束字符而不從另一個搜索中獲取它們。例如:想要匹配任何具有空格、逗號或分號以及開頭和結尾的“狗”或“貓”。所以:“狗狗,貓貓;”將匹配“狗”,“狗”,“貓”。到目前為止,我所擁有的 (?:[ ,;]|^)(cat|dog)(?:[ ,;]|$) 將返回 "dog" "cat" 因為在匹配之間使用空格
查看完整描述

1 回答

?
慕無忌1623718

TA貢獻1744條經驗 獲得超4個贊

我真的只看到用 Go 做這件事的幾種方法。


最直接的方法是只匹配一側,然后做一些后正則表達式邏輯:


https://play.golang.org/p/1_4fi-4kMhi


content := []byte("dog dog, cat cats; ")

re := regexp.MustCompile(`(?:[ ,;]|^)(cat|dog)`)

matches := re.FindAllIndex(content, -1)

for _, match := range matches {

    next := string(content[match[1]])

    if next == "," || next == " " || next == ";" {

        fmt.Println(string(content[match[0]:match[1]+1]))

    }

}

另一種方法是復制任何分隔符:


https://play.golang.org/p/krDlmHfepA1


content := []byte("dog dog, cat cats; ")

re := regexp.MustCompile(`([ ,;])`)

content = re.ReplaceAll(content, []byte("$1$1"))

fmt.Println(string(content))

re = regexp.MustCompile(`(?:[ ,;]|^)(cat|dog)(?:[ ,;]|$)`)

matches := re.FindAllSubmatch(content, -1)

for _, match := range matches {

    for _, submatch := range match[1:] {

        fmt.Println(string(submatch))    

    }

}


查看完整回答
反對 回復 2022-06-13
  • 1 回答
  • 0 關注
  • 116 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號