in reply to Re: Capturing everything after an optional character in a regex?
in thread Capturing everything after an optional character in a regex?

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!