Re: regexps [was: aterm] - off-topic, wot

Greg Anderson (Nifft@FutureRealms.com)
Wed, 14 Apr 1999 17:29:26 -0400


> Henning Percy wrote:
> 
> On Wed, Apr 14, 1999 at 09:46:09AM -0400, Simon Drabble wrote:
> 
> > > Does anyone have a regular expression that would identify this:
> > > [+|-]digit
> > > Testing for a digit or a leading + or - is easy, but I can't
> > > come up with a regular expression that will identify a string
> > > as a digit that may or may not have a leading plus or minus sign.
> > > Thanks.
> > 
> >        I'd probably use something like:
> >
> >        ([-+]?)([0-9]+)
> >
> >        assuming that it's jsut for integers.
> > Put brackets round each part, just to make sure and then join them
> > together gives:
> 
>         ([-+]?)([0-9]+)

I'm using regexp in Tcl and it seems to be both a parser and a regexp 
test. With the Tcl regexp ([-+]?)([0-9]+) returns true for -abc 
because of the separate grouping.  When I use ([-+]?[0-9]+) this it 
works better but still returns true for -12cd.


> Andre Pang wrote:
>
>    If your regular expression engine doesn't support +'s and |'s 
> (eg some versions of grep), try:
>
>    [+-]?[0-9][0-9]*
>
>  You'd also need to put a ^ at the beginning as well as a $ at the end

That's it!  Thanks.  By grouping the whole expression and adding ^$ to 
it I was able to finally test for integers with possible leading 
+- characters.  I had been beating my head against the wall trying to 
make it work.  

regexp {(^[-+]?[0-9]+$)}

Returns true for 123 -123 +123 and not for 1a3 -1a3 +1a3

Thanks everyone for help on this.

-- 

Greg Anderson
http://www.FutureRealms.com/

--
   WWW:   http://www.afterstep.org/
   FTP:   ftp://ftp.afterstep.org/
   MAIL:  http://www.caldera.com/linuxcenter/forums/afterstep.html