Using bash, I can check to see if the value of a variable matches a regular expression. However, I cannot find a way of returning the part that matched. Is this possible?
For example take $test
as test="123456-name-goes-here.1.2.3-something.zip"
The part I'd like to return is 1.2.3-something
.
With the code below, I can successfully match $test
, but I don't know where to go from here.
[[ $test =~ ([0-9]\.[0-9](\.[0-9])?(\.[0-9])?)(-[a-z-]*)? ]] && echo "matched"
The $BASH_REMATCH[0]
will contain the value you need:
test="123456-name-goes-here.1.2.3-something.zip"
reg="[0-9]\.[0-9](\.[0-9])?(\.[0-9])?(-[a-z-]*)?"
if [[ $test =~ $reg ]]; then
echo ${BASH_REMATCH[0]};
fi
See the IDEONE demo
See this cheatsheet :
Regular expression captures will be available in
$BASH_REMATCH
,${BASH_REMATCH[1]}
,${BASH_REMATCH[2]}
, etc.
That means that the whole match value is stored in ${BASH_REMATCH}
with Index = 0, and the subsequent items cotnain submatches that were captured with (...)
(capturing groups).
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.