我一直在替换运算符中尝试几个正则表达式:
$str =~ s/^0+(.)/$1/;
将0000转换为0,将0001转换为1
$str =~ s/^0+./$1/;
将0000转换为空字符串,000100转换为00,0001100转换为100.
圆括号有什么区别?
解决方法
这似乎有点误用我 – 你需要()来确定你的匹配.
http://perldoc.perl.org/perlre.html
Capture buffers
The bracketing construct ( … )
creates capture buffers. To refer to
the current contents of a buffer later
on,within the same pattern,use \1
for the first,\2 for the second,and
so on. Outside the match use “$”
instead of “\”. (The \ notation
works in certain circumstances outside
the match. See the warning below about
\1 vs $1 for details.) Referring back
to another part of the match is called
a backreference.
所以基本上你可以使用
if ($str =~ /^0+(.)/) { print "matched $1"; }
如果你有多个分组匹配,它们将是1美元,2美元,3美元……等等
if($str =〜/(0 *)(1 *)/){print“我有$1和$2”; }