看起来你而过以为你正则表达式。您正在寻找由一些非单词字符分隔的两个单词字符序列。
if ($line =~ /(\w+)\W+(\w+)/) {
say "$1/$2";
}
一个更简单的方法是将匹配单词字符的所有序列:
if (my @words = $line =~ /(\w+)/g) {
say join '/', @words;
}
更新:我把你的正则表达式到这个regex explainer。这里的一下就出来了:
NODE EXPLANATION
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
# '#'
--------------------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
\S+ non-whitespace (all but \n, \r, \t, \f,
and " ") (1 or more times (matching the
most amount possible))
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
\t '\t' (tab)
--------------------------------------------------------------------------------
\^ '^'
--------------------------------------------------------------------------------
( group and capture to \2:
--------------------------------------------------------------------------------
% '%'
--------------------------------------------------------------------------------
) end of \2
--------------------------------------------------------------------------------
s* 's' (0 or more times (matching the most
amount possible))
--------------------------------------------------------------------------------
( group and capture to \3:
--------------------------------------------------------------------------------
\S+ non-whitespace (all but \n, \r, \t, \f,
and " ") (1 or more times (matching the
most amount possible))
--------------------------------------------------------------------------------
) end of \3
我觉得你最大的问题是,你试图在正则表达式的中间相匹配的文字^
,但%
周围的转义括号是一个问题了。并且是毫无意义和令人困惑的:-)
尝试'$ line =〜/ ^#\ W *(\ w +)\ t \ W *(\ w +)/' –
括号是正则表达式中的特殊字符, 。 – Toto