Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return RegEx match in bash

Tags:

regex

bash

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"
like image 907
David Gard Avatar asked Dec 01 '25 04:12

David Gard


1 Answers

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).

like image 60
Wiktor Stribiżew Avatar answered Dec 02 '25 20:12

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!