Ok, here's my attempt after Anonymous monk's intention is clear.

$string =~ m/(?:(?=.*?X)X|(?!.*?X))(\S+)/;
And here's a little test -

$string1="abcX123"; $string2="abc123"; $string1 =~ m/(?:(?=.*?X)X|(?!.*?X))(\S+)/; print "$1\n"; $string2 =~ m/(?:(?=.*?X)X|(?!.*?X))(\S+)/; print "$1\n";
And the output is as expected, and both in $1 -
123 abc123
And the tricky bit in the above regex is the (?:(?=.*?X)X|(?!.*?X)) part, which defines an optional anchor point.


Update: I hit my head on the wall a couple of times, literally, after I saw sauoq's much clever solution below. I was locked up with the idea of an optional anchor point, that I have failed to notice the vital bit of the clue - capture till the end, that defined a fixed anchor point to look back from, instead of a floating anchor point that looks forward. Although my solution worked, it was way too complicated than is necessary.

An important lesson I have learnt today: when a problem seems rather complicated, take a step back and look for other clues. The alternative solution is probably staring right in my face!


In reply to Re: Re: Capturing everything after an optional character in a regex? by Roger
in thread Capturing everything after an optional character in a regex? 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.