You can use a look-ahead like this

use strict; use warnings; my $str = q{abcdceefghfty}; for my $ch (qw(a b c d e f g)) { print qq{"$ch" Unique in "$str"\n} if $str !~ m{($ch)(?=.*\1)}; }

which produces

"a" Unique in "abcdceefghfty" "b" Unique in "abcdceefghfty" "d" Unique in "abcdceefghfty" "g" Unique in "abcdceefghfty"

Cheers,

JohnGG

Update: The above approach is flawed in that testing for a character that doesn't occur in the string at all would still succeed and show as unique. This is because testing that the string doesn't match multiple characters is also true if there are no characters.

The amended script below changes by looking for positive matches of a single character. It is a touch more complex because of the need to interpolate the character being sought into a negated character class, hence the qr{...}. Looking for a hard-coded character is simpler, e.g. to check that "c" was unique, $str =~ m{\A[^c]*(c)(?!.*\1)} would work. Here's the amended script.

use strict; use warnings; my $str = q{abcdceefghfty}; for my $ch (q{a} .. q{z}) { my $matchTxt = q {\A} . qq{[^$ch]*($ch)} . q {(?!.*\1)}; my $rxUniq = qr{$matchTxt}; print qq{"$ch" unique in "$str"\n} if $str =~ $rxUniq; }

In reply to Re: Unique character in a string? by johngg
in thread Unique character in a string? by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.