Re: alternation option end of string
Ray Andrews <[email protected]> Sat, 2 May 2026 09:59:12 -0700
| Newsgroups | gmane.comp.shells.zsh.devel,gmane.comp.shells.zsh.user |
|---|---|
| Message-ID | <[email protected]> |
On 2026-05-02 02:47, Roman Perepelitsa wrote:
> This should do it, if I understood your requirements correctly:
>
> ${${(M)string:#cat(|s*)}[1,4]}
But the length of the string is arbitrary I can't use any sort of length.
>
> Another option would be to capture the interesting part of the match
> explicitly (requires extended_glob):
>
> [[ $string == (#b)((cat)|(cats)*) ]] && out=$match[2]$match[3] || out=
That tests fine. Too bad what Mark said about using the '$' to test for
the end of the string seems not to work, it would have been simpler. In
my actual situation I'm testing for a comma then a number, and only a
number, either at the end of the string OR followed by another comma
and then anything or nothing else:
[[ $remainder == (#b)(,(<->)|,(<->),*) ]] && s_idx=$match[2]$match[3]
In practice I'm breaking filenames into a base, an index and any
following comment, it's part of my backup system. It's been 99% perfect
for a long time, but there's always another gotcha and one showed up a
few days ago and it's an exercise to get it bloody perfect, which I did,
but it was a bit convoluted. Your way is much better. Here's some
tortures:
INPUT: file
base: file
idx:
comment:
INPUT: file,
base: file
idx:
comment:
INPUT: file,8
base: file
idx: 8
comment:
INPUT: file,88
base: file
idx: 88
comment:
INPUT: file,8,comment
base: file
idx: 8
comment: comment
INPUT: file,88,comment
base: file
idx: 88
comment: comment
INPUT: file,8a
base: file
idx:
comment: 8a
INPUT: file,a8
base: file
idx:
comment: a8
INPUT: file,a8,comment
base: file
idx:
comment: a8,comment
INPUT: file,8a,comment
base: file
idx:
comment: 8a,comment
INPUT: file,8a,com,ment
base: file
idx:
comment: 8a,com,ment
INPUT: file,8,com,ment
base: file
idx: 8
comment: com,ment
INPUT: file,8,comm,9
base: file
idx: 8
comment: comm,9
INPUT: file,8,comm,9a
base: file
idx: 8
comment: comm,9a
INPUT: file,8,comm,a9
base: file
idx: 8
comment: comm,a9
... but there's probably still some lurking gotcha that might sneak
thru. Hard to think up every possible torture.