Check if the string starts with a possible range of values โ€‹โ€‹and retrieves the match

Given the following JavaScript code:

const branch = 'PRODUCT-1234-foobar';
const match = (/^(?:product|core|shop)-\d+/i).exec(branch);
const name = match ? match[0] : 'unknown';

      

For a branch starting with PRODUCT-

, CORE-

or SHOP-

, followed by at least one number, this will give me the first part of the branch name, in this case PRODUCT-1234

.

I've tried to do the same thing in Bash, but I can't seem to get it to work. How should I do it? The answer should preferably be case insensitive.

+3


source to share


1 answer


You can use shopt -s nocasematch

to make subsequent match case insensitive (see this source ).

Using

shopt -s nocasematch
branch='PRODUCT-1234-foobar'
reg="^(product|core|shop)-[0-9]+"
if [[ $branch =~ $reg ]]; then
    echo ${BASH_REMATCH[0]};
fi

      

Watch the online demo .



Template details

  • ^

    - beginning of line
  • (product|core|shop)

    - one of the alternatives
  • -

    - hyphen
  • [0-9]+

    - one or more digits.

${BASH_REMATCH[0]}

indicates the full value of the match.

+2


source







All Articles