简体   繁体   中英

Multiline Bash Regex Match

I've been reading through tons of threads about this, but none have helped me yet.

This is a sample of my text:

    [userId:@"1"
        userName:@""
            userPos:@[@"11006321C", ]
         userDisp:@[@"4200012FD6", ]];



[userId:@"2"
        userName:@""
            userPos:@[@"412520084C",
                     @"7200851", 
                     @"54720021", 
                     ]
        userDisp:@[@"230035FD6", 
                     @"3213456432C0035FD6", 
                     @"1F200538D5", 
                     ]];

I'm trying to capture this:

userPos:@[@"11006321C", ]
         userDisp:@[@"4200012FD6", ]]

and

userPos:@[@"412520084C",
                     @"7200851", 
                     @"54720021", 
                     ]
        userDisp:@[@"230035FD6", 
                     @"3213456432C0035FD6", 
                     @"1F200538D5", 
                     ]]

(All matches from the text) using regex: userPos:@\\[((?:.\\r?\\n?)*)\\]

Trying it in bash using:

for string in $file # text has been read into this variable
do
    [[ $word =~ $regex ]]
    if [[ ${BASH_REMATCH[0]} ]]
    then
        string="${x:+x }${BASH_REMATCH[0]}"
        userlist+=("$string")
        echo "$string"
    fi
done

To append them to a list.

But this doesn't work since the regex matches noting at all. I know there are different kinds of Regex engines and stuff, and I've tried so many different regexes for this to work in bash, but can't seem to get it to work.

Anyone who could help me capture what I want in bash?

The regex you're looking for is userPos:([^;]*)] .

regex="userPos:([^;]*)]"
while [[ $text =~ $regex ]]
do
    string="${x:+x }${BASH_REMATCH[0]}"
    userlist+=("$string")
    echo "$string"
    text=${text#*"${BASH_REMATCH[0]}"}
done

$text is your text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM