加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Perl正则表达式中的括号有什么作用?

发布时间:2020-12-16 06:16:13 所属栏目:大数据 来源:网络整理
导读:我一直在替换运算符中尝试几个正则表达式: $str =~ s/^0+(.)/$1/; 将0000转换为0,将0001转换为1 $str =~ s/^0+./$1/; 将0000转换为空字符串,000100转换为00,0001100转换为100. 圆括号有什么区别? 解决方法 这似乎有点误用我 – 你需要()来确定你的匹配. ht
我一直在替换运算符中尝试几个正则表达式:

$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”; }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读