7stud has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

If I have a set of characters like a-z, how can I match one of those characters followed by another character in the group--but not the same one that matched? For instance, if the group first matches 'd', then the subsequent character should match a character in a-ce-z. I wish I could write:

([a-z] - \1)

Replies are listed 'Best First'.
Re: match character in a set, them match one of the other ones
by BrowserUk (Patriarch) on Aug 18, 2011 at 02:57 UTC

    Updated per moritz correction below.

    So:

    print $1 while 'hello' =~ m[(([a-z])(?!\2)[a-z])]g;; he lo

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      That dot should probably be replaced by [a-z], if I understood the original question correctly.

        Indeed. Corrected above.

Re: match character in a set, them match one of the other ones
by 7stud (Deacon) on Aug 18, 2011 at 05:48 UTC
    Is that your final answer?
      Is that your final answer?

      Sorry, I just noticed this. Is that question aimed at you, me, or the world in general?


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.

        At you. moritz provided the fix. In addition to moritz's correction, you can also clean up your regex by eliminating the extraneous parentheses, which just serve to obfuscate what is going on:

        use strict; use warnings; use 5.010; my @strings = ( 'aa', 'ab', 'a1', ); for my $str (@strings) { if ($str =~ / ([a-z]) (?!\1) [a-z] /x ) { say "$str: $1"; } } --output:-- ab: a

        Thanks.