Re: Can a regex match numbers?

From: Tore Aursand (tore_at_aursand.no)
Date: 11/18/03


To: beginners@perl.org
Date: Tue, 18 Nov 2003 19:54:31 +0100

On Tue, 18 Nov 2003 16:37:06 +0000, Jabez Wilson wrote:
> Is it possible to specify number matching in a regex, i.e. can you have
> something like:
>
> my $match =~ m/match_number_if_number_is_less_than_255/
>
> instead of my $match =~ m/(\d{3})/;
>
> if ($1<=255){my @array = @array +$1}?

Yes, but would you? IMO, using regular expressions to check the value of
something creates less readable code. I tend to prefer to first check if
I'm really dealing with a number, and then checking the value of it in a
good old fashion way;

  if ( $nr =~ m,^[-+]?\d+$, && $nr < 255 ) {
      # Match
  }

I don't need to write that regular expression every time, of course,
'cause I've been nice enough to put it in a module so that I only need to
write 'is_int($nr)' each time.

(And the actual implementation of the is_int() function is heavier; It
check if a number really _is_ a number - the above don't, really...)

-- 
Tore Aursand <tore@aursand.no>


Relevant Pages

  • Re: regex, negations, grep, find and replace (a few questions)
    ... I do not know much regex. ... But it seems as if you define each character ... be aware that different tools may use slightly different syntaxes for the same regular expressions. ... expresion" might mean "matching everything not matching the regular expression" or, in other words, removing everything matching the regexp. ...
    (alt.os.linux)
  • Re: Search for multiple things in a string
    ... >> I also feel that Regular Expressions, being an object in asp.net (not ... So using Regex is not really like using another language (as C# is different ... I agree with you that readability is important. ... And I was not saying experiment with it. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: for a laught (???)
    ... Regex doesn't work too well with a null byte delimiter :-) ... the API for a particular form of regular expressions ... Regex doesn't work with null terminated strings. ... qualifier or the qualifier "commonly" might have suggested. ...
    (comp.lang.cobol)
  • Re: function to match parenthesis ( and )
    ... to have a collection with all matching subelements. ... There some case about little changes where the regex modification is ... function between the first parenthesis to match. ... >>> inappropriate places to apply regular expressions. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Search for multiple things in a string
    ... >>> As far as readability, it has nothing to do with Regular Expressions ... > and Regex. ... >> characters in the string, perhaps even writing your own state machine ...
    (microsoft.public.dotnet.languages.csharp)