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

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

我可以確認字符串是否與我的正則表達式中的第一個塊匹配嗎

我可以確認字符串是否與我的正則表達式中的第一個塊匹配嗎

Go
POPMUISE 2023-02-06 14:40:42
我有以下代碼:package mainimport (    "fmt"    "regexp")func main() {    str := "This is a delimited string, so let's go"    re := regexp.MustCompile(`(?i)(This is a delimited string)|delimited|string`)    matches := re.FindAllString(str, -1)    fmt.Println("We found", len(matches), "matches, that are:", matches)}并獲得輸出為:We found 1 matches, that are: [This is a delimited string]如果我將str上面代碼中的更改為:str := "This is not a delimited string, so let's go"然后我得到的輸出是:We found 2 matches, that are: [delimited string]兩者都是正確的,但在str具有的第一個塊中與我的正則表達式中的第一個塊1 match匹配,而在顯示 2 個匹配項的第二個塊中,沒有一個與我的正則表達式中的第一個塊匹配。100%This is a delimited stringstr有沒有辦法,所以我知道是否str與我的正則表達式中的第一個塊匹配,以便我得到完全匹配or部分匹配is thelen(matches)` 不為零,但正則表達式中的第一個塊不匹配!
查看完整描述

1 回答

?
HUH函數

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

這個正則表達式:

(?i)(This is a delimited string)|delimited|string

匹配這些文字字符串的最左邊最長的匹配項:

  • This is a delimited string,

  • delimited, 或者

  • string

將文本This is a delimited string, so let's go提供給正則表達式,第一個選項匹配。它是唯一的匹配項,因為它同時消耗了delimitedstring- 搜索在匹配項之后繼續進行。

將您的替代文本This is not a delimited string, so let's go提供給正則表達式會產生 2 個匹配項,因為第一個替代文本不匹配,但第二個 ( delimited) 和第三個 ( string) 匹配。

如果您想知道匹配備選方案,只需將每個備選方案括在括號中以使其成為捕獲組

(?i)(This is a delimited string)|(delimited)|(string)`

現在我們可以檢查每個捕獲組的值:如果它的長度大于 1,則它是匹配的備選方案。

https://goplay.tools/snippet/nTm56_al__2

package main


import (

    "fmt"

    "regexp"

)


func main() {

    str := "This is a delimited string, so let's go and find some delimited strings"


    re := regexp.MustCompile(`(?i)(This is a delimited string)|(delimited)|(string)`)


    matches := re.FindAllStringSubmatch(str, -1)


    fmt.Println("Matches:", len(matches))

    for i, match := range matches {

        j := 1

        for j < len(match) && match[j] == "" {

            j++

        }

        fmt.Println("Match", i, "matched alternative", j, "with", match[j])

    }


}


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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