in reply to Simple Regex drives me insane
tl,dr: I recommend forgetting about setting $1 and using
my $match = /#(\S*)/ ? $1 : "";
First, some assumptions since the specs aren't clear.
The following is a single match that produces the desired result:
/ ^ [^#]* \#? ( \S* ) /x; say $1;
(Update: There's a much simpler approach using (?|pattern). See tybalt89's answer.)
If it doesn't have to be a single match, you could also use the following:
/()/; /#(\S*)/; say $1;
/#(\S*)/ || /()/; say $1;
That said, I think setting a variable other than $1 would be better. This allows us to use one of the following:
my $match = /#(\S*)/ ? $1 : ""; say $match;
my $match = /#\K\S*/ ? $& : ""; say $match;
And if it's acceptable to produce undef instead of an empty string when the pattern isn't found, you could even use the following:
my ( $match ) = /#(\S*)/; say $match;
These are far more readable and maintainable. Among other things, this makes them far less error-prone.
Also, these would be trivial to adapt them to match more restrictive patterns. For example,
my $match = /#(\S+)/ ? $1 : ""; say $match;
my $match = /#(\w+)/ ? $1 : ""; say $match;
Adapting the first version would be horrible.
/ ^ (?: (?! \#\S ). )* \#? ( \S* ) /x; # /#(\S+)/ say $1;
/ ^ (?: (?! \#\w ). )* \#? ( \w* ) /x; # /#(\w+)/ say $1;
|
|---|