简体   繁体   中英

bash regex match or not

I created this regex:

'^CPU\s+LOAD\:\s+([0-9]{1,3})\s+Average\:\s+([0-9]{1,3}).?$'

to match and extract values from my string:

"CPU LOAD: 100 Average: 89"

but occasionally the values will not be available such as:

"CPU LOAD: Average: 89"

"CPU LOAD: 100 Average: "

"CPU LOAD: Average: "

and it will not match, but I need it as a place holder to return "" when values are not present.

So I have tried several things and I think this:

'^CPU\s+LOAD\:\s+([[0-9]{1,3}]?)\s+Average\:\s+([[0-9]{1,3}]?).?$'

should work, but it doesn't seem to be. Is this correct syntax?

This is my test code that wants to fail answer 1 I followed the link and it seems to work at the link page.

rx='^CPU\s+LOAD\:\s+(?:([0-9]{1,3})\s+)?Average:(?:\s+([0-9]{1,3}))?$'
line="CPU LOAD: 89 Average: 99"
  if [[ $line =~ $rx ]]; then
    printf "\n\n${BASH_REMATCH[1]} ${BASH_REMATCH[2]}\n\n"
  else
    printf "\n\nDidn't Match\n\n"
  fi

I updated

rx='^CPU\ +LOAD\:\ +(([0-9]{1,3})\ +)?Average:(\ +([0-9]{1,3}))?$'

and "CPU LOAD: 100 Average: 89" passes

"CPU LOAD: Average: 89" passes

"CPU LOAD: 100 Average: " fails

The latest updates require me to:

 printf "\n\n${BASH_REMATCH[1]} ${BASH_REMATCH[2]} ${BASH_REMATCH[3]} ${BASH_REMATCH[4]}\n\n"

To capture everything and puts either single value into

${BASH_REMATCH[1]} ${BASH_REMATCH[2]}

Thanks for Forth Bird's help. This is the final code that works for my needs.

rx='^CPU\s+LOAD:\s+(([0-9]{1,3})\s+)?Average:(\s+([0-9]{1,3}))?.?$'

What you might do is use an optional non capturing group:

^CPU[[:blank:]]+LOAD\\:[[:blank:]]+(([0-9]{1,3})[[:blank:]]+)?Average:([[:blank:]]+([0-9]{1,3}))?$

See the regex demo

You could match the space by escaping it or use [[:blank:]] to match a whitespace or a tab.

rx='^CPU[[:blank:]]+LOAD\:[[:blank:]]+(([0-9]{1,3})[[:blank:]]+)?Average:([[:blank:]]+([0-9]{1,3}))?$'
line="CPU LOAD: 89 Average: 99"
if [[ $line =~ $rx ]]; then
    printf "\n\n${BASH_REMATCH[2]} ${BASH_REMATCH[4]}\n\n"
else
    printf "\n\nDidn't Match\n\n"
fi

Demo

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