免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2602 | 回复: 5
打印 上一主题 下一主题

一个简单的替换问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2014-10-11 16:04 |只看该作者 |倒序浏览
我有一个字符串,比如$a="a-afoa-fd--f----a", 我需要在每两个字母间插入一个0,我的命令是$a=~s/(\w)(\w)/$1\0$2/g,有错误,请大家指点,非常谢谢!!

论坛徽章:
8
技术图书徽章
日期:2013-08-22 11:21:28未羊
日期:2015-01-19 22:22:25巳蛇
日期:2014-08-11 16:53:08子鼠
日期:2014-05-29 09:04:44摩羯座
日期:2014-04-11 14:15:07丑牛
日期:2014-01-24 12:41:28金牛座
日期:2013-11-21 17:38:28射手座
日期:2015-01-21 08:50:32
2 [报告]
发表于 2014-10-11 16:55 |只看该作者
  1. perl -e '$a="a-afoa-fd--f----a";$a=~s/(\w)(\w)/${1}0${2}/g;print $a'
  2. a-a0fo0a-f0d--f----a
复制代码

论坛徽章:
0
3 [报告]
发表于 2014-10-11 17:58 |只看该作者
谢谢Huang, 我理解如何处理0, 但您的输出中fo之间少了一个0。应该是a-a0f0o0a-f0d--f----a才对呀?

论坛徽章:
145
技术图书徽章
日期:2013-10-01 15:32:13戌狗
日期:2013-10-25 13:31:35金牛座
日期:2013-11-04 16:22:07子鼠
日期:2013-11-18 18:48:57白羊座
日期:2013-11-29 10:09:11狮子座
日期:2013-12-12 09:57:42白羊座
日期:2013-12-24 16:24:46辰龙
日期:2014-01-08 15:26:12技术图书徽章
日期:2014-01-17 13:24:40巳蛇
日期:2014-02-18 14:32:59未羊
日期:2014-02-20 14:12:13白羊座
日期:2014-02-26 12:06:59
4 [报告]
发表于 2014-10-11 20:24 |只看该作者
回复 3# pony2001mx

$ perl -le '$a="a-afoa-fd--f----a";$a=~s/(\w)(?=\w)/${1}0/g;print $a'
a-a0f0o0a-f0d--f----a


more detail information
$ perldoc perlre
NAME
    perlre - Perl regular expressions

DESCRIPTION
    This page describes the syntax of regular expressions in Perl.
    ...
    Look-Around Assertions
              Look-around assertions are zero-width patterns which match a
              specific pattern without including it in $&. Positive assertions
              match when their subpattern matches, negative assertions match
              when their subpattern fails. Look-behind matches text up to the
              current match position, look-ahead matches text following the
              current match position.

                "(?=pattern)"
                  A zero-width positive look-ahead assertion. For example,
                  "/\w+(?=\t)/" matches a word followed by a tab, without
                  including the tab in $&.
                ...

论坛徽章:
0
5 [报告]
发表于 2014-10-11 21:55 |只看该作者
本帖最后由 zwin506 于 2014-10-11 21:58 编辑

#!/usr/bin/perl
my $a="a-afoa-fd--f----a";
my @chars=split//,$a;
my $max=$#chars;
my $string;
for(my $i=0;$i<$max;$i++){
        if($chars[$i]=~m/\w/ and $chars[${i}+1]=~m/\w/){
                print $chars[$i]."0";
        }else{
                print $chars[$i];
        }
}
print "\n";

运行结果:a-a0f0o0a-f0d--f----
(正则表达式的那个方法很不错(?=\w),我试试其他的办法,看来也行。)

论坛徽章:
0
6 [报告]
发表于 2014-10-12 09:51 |只看该作者
谢谢 jason680等人的回复,我明白了很多道理,谢谢!
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP