1

My problem might be solvable in other ways, but I can't help but wonder why it doesn't work using regex.

The code

#!/bin/bash
python_version=$(python3 --version)
regexp='(?<=^Python )3\.[0-9]+'
[[ $python_version =~ $regexp ]]
echo $BASH_REMATCH

should yield 3.8 for python version 3.8.10, for example. And it does, when I check it at regex101.com. But when I stick it in the bash, it does nothing.

I should note, that $python_version equals to Python 3.8.10 in this test case.

I would really like to know, how to solve this particular problem using bash only.

I'm using Ubuntu 20.04.

winwin
  • 125
  • 5

1 Answers1

2

Positive lookbehind ((?<=…)) does not work in POSIX ERE used by [[ … =~ … ]].

In your use case you can match a broader pattern and remove the excessive part later:

#!/bin/bash
python_version=$(python3 --version)
regexp='^Python 3\.[0-9]+'
[[ $python_version =~ $regexp ]]
echo "${BASH_REMATCH#Python }"

Note this approach wouldn't work for arbitrary regex instead of your ^Python . In ${var#pattern} the pattern is like filename generation pattern, not a regex. See this another answer of mine.

Kamil Maciorowski
  • 69,815
  • 22
  • 136
  • 202
  • I'm able to successfully use it, thank you, but I don't understand, what the `${BASH_REMATCH#Python }` piece does. Could you, please, explain? – winwin Aug 17 '21 at 23:06
  • @winwin Have you seen the linked answer and the example there? `${parameter#[word]}`, Remove Smallest Prefix Pattern. Or are you asking about `$BASH_REMATCH` you used first and I followed? – Kamil Maciorowski Aug 18 '21 at 02:46