Matching optional parameters with non-capturing groups in Bash regular expression

前端 未结 2 1402
有刺的猬
有刺的猬 2021-01-18 06:04

I want to parse strings similar to the following into separate variables using regular expressions from within Bash:

Category: entity;scheme=\"http://schemas         


        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-18 06:30

    You can emulate non-matching groups in bash using a little bit of regexp magic:

                  _2__    _4__   _5__
    [[ "fu@k" =~ ((.+)@|)((.+)/|)(.+) ]];
    echo "${BASH_REMATCH[2]:--} ${BASH_REMATCH[4]:--} ${BASH_REMATCH[5]:--}"
    # Output: fu - k
    

    Characters @ and / are parts of string we parse. Regexp pipe | is used for either left or right (empty) part matching.

    For curious, ${VAR:-} is variable expansion with default value in case $VAR is empty.

提交回复
热议问题