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!
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.