You are not logged in.

#1 2014-05-11 18:11:55

ninian
Member
From: United Kingdom
Registered: 2008-02-24
Posts: 726
Website

[alternative found] Can this Bash regex be stated more slickly?

I need to match the following four patterns of a filename (a,b,c,d are arbitrary characters; . X and ext are literal characters) in a Bash script, and here's the regex which works for me:

file='ab.'
file='ab.Xcd'
file='ab.ext'
file='ab.extXcd'

[[ $file =~ (\.$|\.X|\.ext$|\.extX) ]] && echo matches

What I wonder is whether this can be stated more succinctly using () grouping and a repetition operator such as * ? +
I tried a few possibilities but the only expression I could get working right was the one above.
Any help gratefully received!

Last edited by ninian (2014-05-11 20:00:37)

Offline

#2 2014-05-11 18:50:25

falconindy
Developer
From: New York, USA
Registered: 2009-10-22
Posts: 4,111
Website

Re: [alternative found] Can this Bash regex be stated more slickly?

Well, I wouldn't use regex here.

[[ $file = *.?(ext)?(X??) ]] && echo "$file matches"

Offline

#3 2014-05-11 19:59:35

ninian
Member
From: United Kingdom
Registered: 2008-02-24
Posts: 726
Website

Re: [alternative found] Can this Bash regex be stated more slickly?

falconindy wrote:

Well, I wouldn't use regex here.

[[ $file = *.?(ext)?(X??) ]] && echo "$file matches"

Aha - thank you very much - seems to do the trick, and more understandable too.
smile

Offline

Board footer

Powered by FluxBB