Home: Perl Programming Help: Regular Expressions:
match a string with 4 digits but not 1111



LarryLoser
New User

Jan 18, 2013, 6:20 PM


Views: 15399
match a string with 4 digits but not 1111

I am having a brain cramp.

How can I match a string with 4 consecutive digits so long as they are not 1111?

dsjhsd 1234 dfddf = match

sdadad1114jkgjhg = match

dassfa1111jhgj = no match

sdad123dfasfd = no match


LarryLoser
New User

Jan 18, 2013, 7:58 PM


Views: 15395
Re: [LarryLoser] match a string with 4 digits but not 1111

I got it

$string =~ /(?!1111)\d{4}/


BillKSmith
Veteran

Jan 18, 2013, 8:41 PM


Views: 15393
Re: [LarryLoser] match a string with 4 digits but not 1111

That sure does not look right, but I cannot make it fail. Could anyone please explain.
Good Luck,
Bill


FishMonger
Veteran / Moderator

Jan 18, 2013, 9:48 PM


Views: 15389
Re: [BillKSmith] match a string with 4 digits but not 1111


Code
use strict; 
use warnings;
use v5.10.1;
use YAPE::Regex::Explain;

my $REx = '/(?!1111)\d{4}/';
say YAPE::Regex::Explain->new($REx)->explain;



Code
The regular expression: 

(?-imsx:/(?!1111)\d{4}/)

matches as follows:

NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
/ '/'
----------------------------------------------------------------------
(?! look ahead to see if there is not:
----------------------------------------------------------------------
1111 '1111'
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
\d{4} digits (0-9) (4 times)
----------------------------------------------------------------------
/ '/'
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------