Non-greedy regular expression match for multicharacter delimiters in awk

前端 未结 3 1580
后悔当初
后悔当初 2020-12-20 00:14

Consider the string \"AB 1 BA 2 AB 3 BA\". How can I match the content between \"AB\" and \"BA\" in a non-greedy fashion (in awk)?

3条回答
  •  眼角桃花
    2020-12-20 00:51

    For general expressions, I'm using this as a non-greedy match:

    function smatch(s, r) {
        if (match(s, r)) {
            m = RSTART
            do {
                n = RLENGTH
            } while (match(substr(s, m, n - 1), r))
            RSTART = m
            RLENGTH = n
            return RSTART
        } else return 0
    }
    

    smatch behaves like match, returning:

    the position in s where the regular expression r occurs, or 0 if it does not. The variables RSTART and RLENGTH are set to the position and length of the matched string.

提交回复
热议问题