【问题标题】:match position of all matched character in string with regexp in bash用bash中的正则表达式匹配字符串中所有匹配字符的位置
【发布时间】:2013-04-16 20:07:37
【问题描述】:

我正在尝试通过正则表达式匹配特定字符的所有位置。我可以用 expr index 做到这一点,但这只匹配字符串中的第一个字符。

echo $(expr index "$z" '[\x1F\x7F-\x9F]') 

注意:$z 是包含字符串的 var

这(正确)返回:

6

我知道在这个字符串中,我在位置 6 和 12 有两个匹配的字符,我想返回匹配字符的所有位置,而不仅仅是第一个。

你能帮帮我吗? 谢谢!

【问题讨论】:

  • 我很确定expr index 不会将正则表达式作为其第二个参数,但我很想弄错。

标签: regex bash hex match


【解决方案1】:

这是一个使用 awk 的命令。它打印所有与正则表达式匹配的位置/0-9/

echo $z | awk  '{s=$0; i=1; idx=0; 
       while(i>0){ 
           i=match(s, /[0-9]/); 
           if(i>0) {
                  idx += i;
                  print idx; 
                  s=substr(s, i+1);
           }
       }
}'

【讨论】:

    【解决方案2】:

    您可能喜欢使用grep

    #!/bin/bash
    
    matches=();
    
    # Used a "Process Substitution" because of the loop's subshell
    while read match
    do
        matches+=( "$match" );
    done \
    < <(
        printf '%s\n%s' \
            'somedata{a917am}some{8ka81a}data' \
            'awd123{ad123d}adad' \
            | grep -Eobn '\{[0-9a-z]{6}\}' # The magic is here
    );
    
    for (( i = 0; i < ${#matches[@]}; i++ ));
    do
        matchRaw="${matches[$i]}";
        match="${matchRaw#*\:}";
        match="${match#*\:}";
        matchLine="${matchRaw%%\:*}";
        matchChar="${matchRaw#*\:}";
        matchChar="${matchChar%%\:*}";
        matchLength="${#match}";
    
        printf 'Match #%s, line %2s, char %2s, length %2s: "%s"\n' \
            "$((i + 1))" \
            "$matchLine" \
            "$matchChar" \
            "$matchLength" \
            "$match";
    done
    

    输出:

    Match #1, line  1, char  8, length  8: "{a917am}"
    Match #2, line  1, char 20, length  8: "{8ka81a}"
    Match #3, line  2, char 39, length  8: "{ad123d}"
    

    grep (GNU grep) 2.25 上工作。

    相关:

    grep --help
    
    # -E, --extended-regexp     PATTERN is an extended regular expression (ERE)
    # -o, --only-matching       show only the part of a line matching PATTERN
    # -b, --byte-offset         print the byte offset with output lines
    # -n, --line-number         print line number with output lines
    

    Process Substitution (from)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-08
      • 1970-01-01
      • 2013-06-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 2017-01-23
      相关资源
      最近更新 更多