dql7588 2019-08-26 07:12
浏览 528
已采纳

Go中字符串末尾的正则表达式匹配失败

I'm trying to test a string against this pattern: "At least one square bracket pair, wrapping 2 digits, followed by at lease one character". For example, [11][22][33]dd should match while [11][22][33] shouldn't.

I've tried this regex: (\[\d{2}])+.+. However, when it is tested against with [11][22][33], which should have failed, it still passes that test. The first + quantifier only matches two groups [11] and [22], while the rest part [33] is matched by .+.

I thought the "greedy" behaviour of the + quantifier would exhaust all the matching segments of the group it modifies; however it seems that the regex engine would place the "exhaust all matching possibilities" principle above the "greedy quantifier" rule, not the way I'd expected.

How should I achieve my goal?

(This question is actually language-agnostic, though tagged with "golang" which is the language I'm currently using.)

  • 写回答

2条回答 默认 最新

  • douzhi7754 2019-08-26 09:23
    关注

    You may use

    re := regexp.MustCompile(`(?:\[\d{2}])+(.*)`)
    match := re.FindStringSubmatch(s)
    if len(match) > 1 {
        return match[1] != ""
    }
    return false
    

    The (?:\[\d{2}])+(.*) pattern matches 1+ occurrences of [, 2 digits, ] and then captures any 0 or more chars other than line break chars into Group 1. Then, if the match was found (if len(match) > 1), true should be returned if the Group 1 value is not empty (match[1] != ""), otherwise, false is returned.

    See Go demo:

    package main
    
    import (
        "fmt"
        "regexp"
    )
    
    func main() {
        strs := []string{
            "[11][22][33]",
            "___[11][22][33]",
            "[11][22][33]____",
            "[11][22]____[33]",
        }
        for _, str := range strs {
            fmt.Printf("%q - %t
    ", str, match(str))
        }
    }
    
    var re = regexp.MustCompile(`(?:\[\d{2}])+(.*)`)
    
    func match(s string) bool {
        match := re.FindStringSubmatch(s)
        if len(match) > 1 {
            return match[1] != ""
        }
        return false
    }
    

    Output:

    "[11][22][33]" - false
    "___[11][22][33]" - false
    "[11][22][33]____" - true
    "[11][22]____[33]" - true
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度