Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Extracting Informations from strings



On Mon, 21 Jun 2004, Peter Stephenson wrote:

> Stefan =?iso-8859-1?Q?Reich=F6r?= wrote:
> >   Battery 1: charging, 95%, charging at zero rate - will never fully charge.
> > 
> > I want to extract the "95%" from the output above.
> 
> setopt extendedglob
> local match mbegin mend
> if [[ $string = (#b)"Battery "*" charging, "(<->)"%"* ]]; then
>   print "Charge is ${match[1]}%"
> fi

To do this without extendedglob and backreferences is, I think, simpler:

	print Charge is ${(M)${(M)string%%<->%,*}##<->%}

This is (where <-> matches a string of digits):

	${(M)string%%<->%,*}	Longest suffix beginning with <->%
	${(M)...##<->%}		Longest prefix of that matching <->%

I'd only resort to backreferences when the substring to be extracted is
ambiguous (e.g. "... charging, 95%, charging at 17%, ...") or when
extracting multiple fields (e.g. both the battery number and the charge
percentage).



Messages sorted by: Reverse Date, Date, Thread, Author