免费注册 查看新帖 |

Chinaunix

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

请教一个正则表达式的问题 - /(\.\w+)?$/ [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-03-07 11:13 |只看该作者 |倒序浏览
Learning Perl 中的题目,请解释一下。
perl -e '$_=abc.eeeee.i;   
s/(\.\w+)?$/.out/;
print;'

结果:abceeeeei.out

结果为什么不是abc.out

论坛徽章:
0
2 [报告]
发表于 2007-03-07 13:19 |只看该作者
$_=abc.eeeee.i;  相当于: $_="abceeeeei";
明白了否?
我的理解就是这样。:wink:

论坛徽章:
1
荣誉版主
日期:2011-11-23 16:44:17
3 [报告]
发表于 2007-03-07 14:08 |只看该作者
$_='abc.eeeee.i';   

s/(\.\w+)+$/.out/;

print;

这样就可以了
输出是 abc.out

论坛徽章:
1
荣誉版主
日期:2011-11-23 16:44:17
4 [报告]
发表于 2007-03-07 14:12 |只看该作者
如果要把 abc.eeeee.i 当成字符串得用引号
这个和你使用的 ? 有关
?是非贪婪的匹配 如果想把   .eeeee.i 都匹配上得用 +

论坛徽章:
0
5 [报告]
发表于 2007-03-07 14:18 |只看该作者
$_="abc.eeeeee.i"
用引用括起来就可以让连接符"."变成字符“."

论坛徽章:
0
6 [报告]
发表于 2007-03-07 17:15 |只看该作者
谢谢各位。
我搞错了。 这是转换文件的扩展名,应该这样才对。
perl -e 'my $in = $ARGV[0];
> my $out = $in;
> $out =~ s/(\.\w+)?$/.out/;
> print "$out\n";' testtest.test.test

结果:testtest.test.out

论坛徽章:
0
7 [报告]
发表于 2007-03-08 11:09 |只看该作者
原帖由 gmxhk 于 2007-3-7 11:13 发表
Learning Perl 中的题目,请解释一下。
perl -e '$_=abc.eeeee.i;   
s/(\.\w+)?$/.out/;
print;'

结果:abceeeeei.out

结果为什么不是abc.out


实话说,LZ的原始问题偶也没看明白...问了下别人解释如下:

$_=abc.eeeee.i;

This is short for:

$_ = 'abc' . 'eeeee' . 'i';

Which is the same as saying:

$_ = 'abceeeeei';


The substitution:

s/(\.\w+)?$/.out/;

Says to match a period (.) followed by one or more 'word' characters (\w+).
This pattern is enclosed in parentheses and this group should match zero or
one time.  The pattern is anchored to the end of the string.  Because the
pattern will always match, the replacement string '.out' will either be
appended to the string or replace any (\.\w+) pattern at the end of the string.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP