On Wed, 24 Aug 2011 20:24:00 +0530, Ramprasad Prasad wrote:
> Assume I have to find the first unique character in a string
>
> $string = "abtable";
>
> # t is the first unique string
>
> I tried using a negative backtrace lookup to get the answer in a single
> regex ... But something is missing.
>
> /(.).(?!\1)/ && print $1;
>
> it seems fine ... But doesn't work
The easier way would be with code instead of a regex:
use strict;
use warnings;
use 5.10.0;
@ARGV or @ARGV = (qw(abtable zzabtable abcabc zbbb abcdefabcdefg q qqq));
OUTER: for ( @ARGV )
{
my @c = split //;
my %n;
$n{$_}++ for @c;
for ( @c )
{
next if $n{$_} > 1;
say;
next OUTER;
}
say "FAIL: $_";
}
% ./proggie
t
t
FAIL: abcabc
z
g
q
FAIL: qqq
But if you really want a regular expression to do the job:
use strict;
use warnings;
use 5.10.0;
@ARGV or @ARGV = (qw(abtable zzabtable abcabc zbbb abcdefabcdefg q qqq));
for ( @ARGV )
{
say
/\A # Starts with
(.*?) # Minimal string, possibly null, then
(.) # Candidate character
(??{ # Evaluate code
index($1,$2) >= 0 # If first capture contains candidate
? '(*FAIL)' # Assert match failure
: '(*ACCEPT)' # Else success
}) # Followed by
(?!.*\2.*) # Chars not containing candidate
/x ? "$1\[$2\]${^POSTMATCH}" : "FAIL: $_";
}
%proggie
ab[t]able
zzab[t]able
FAIL: abcabc
[z]bbb
abcdefabcdef[g]
[q]
FAIL: qqq
--
Peter Scott
http://www.perlmedic.com/ http://www.perldebugged.com/
http://www.informit.com/store/product.aspx?isbn=0137001274
http://www.oreillyschool.com/certificates/perl-programming.php
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/