Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Check a string for consecutive digits

by Anonymous Monk
on Nov 26, 2015 at 00:00 UTC ( [id://1148634]=note: print w/replies, xml ) Need Help??


in reply to Check a string for consecutive digits

Another variant...
use strict; use warnings; my @strings = ( '10203040', '1234', '298761', '4562', '856423', ); my @regexes = ( make_regex( '0123456789', 3 ), make_regex( '9876543210', 3 ), ); for my $string (@strings) { print "Bad string => $string\n" if grep { $string =~ $_ } @regexes; } sub make_regex { my ( $str, $len ) = @_; my @splits = map { substr( $str, $_, $len ) } 0 .. length($str) - $len; my $rx = join '|', map quotemeta, @splits; return qr/$rx/; }

Replies are listed 'Best First'.
Re^2: Check a string for consecutive digits
by mr_ron (Chaplain) on Nov 26, 2015 at 18:05 UTC

    This another variant that uses qr// to check for the 'or' / '|' of all three digit sequences. I just boil it down to one regex here.

    use strict; use warnings; my $dig3_regex_str = join '|', map { ($_, scalar reverse $_) } # 012 and 210 map { join '', $_ .. $_+ 2 } 0..7; # 012, 123, ... my $dig3_regex = qr/$dig3_regex_str/; # Test samples taken from other monks postings ... my @strings = ( '10203040', '1234', '298761', '4562', '856423', 'a12b543c'); for my $string (@strings) { print "Bad string => $string\n" if $string =~ $dig3_regex; }
    Ron

      Your more neat (IMHO) variant is easily made configurable and, like Re: Check a string for consecutive digits, uses no 5.10 regex extensions:

      use constant MIN => 4; my $delta = MIN-1; ;; my ($too_many_consec) = map qr{ $_ }xms, join ' | ', map { $_, scalar reverse $_ } map { join '', $_ .. $_+$delta } 0 .. (9-$delta) ; ...


      Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1148634]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (2)
As of 2024-04-26 01:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found