RegEx in if condition. How?
Hello
I trying to RegEx mpg and mpeg in 'if' condition. It is not working. Code:
if [[ $VAR == "mp4" || $VAR =~ "mp[e]?g" ]] ; then How to do that? Thanks |
Assuming you are using the bash shell, remove the quotes from the regex expression. Quoting all or parts of the regex causes the quoted parts to be matched as a string (man bash of course).
Code:
if [[ $VAR == "mp4" || $VAR =~ mp[e]?g ]] ; then |
Quote:
|
Quote:
So: Code:
$VAR =~ "mp[e]?g" Code:
$VAR =~ "mpe?g" |
Quote:
|
A glob match (==) is "anchored" by default, so you might want to put anchors on the RE match (=~)
Code:
if [[ $VAR == mp4 || $VAR =~ ^mpe?g$ ]] Code:
if [[ $VAR == *mp4* || $VAR =~ mpe?g ]] Often you can do everything in one ERE Code:
if [[ $VAR =~ ^(mp4|mpe?g)$ ]] |
All good advice, but I wonder how expensive the regex engine is ?. Might be better off using the OR test if there is a large disparity in favour of "mp4" and the test can take advantage of short-circuiting.
Just idle musings ... |
yes, a case would be probably better:
Code:
case $VAR in |
All times are GMT -5. The time now is 11:00 PM. |