免费注册 查看新帖 |

Chinaunix

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

如何取字符串内含有不确定字符的子串 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-06-06 09:38 |只看该作者 |倒序浏览
例:ABCDNXXXXNID
其中:XXXX是四位的数字,是可变的。并且NXXXX的位置也是不固定的。
我想将NXXXX这个字串取出来放在一个变量里备用。

正则表达式倒是可以匹配出NXXXX,但是我不知道如何将这个子串取出。

论坛徽章:
0
2 [报告]
发表于 2007-06-06 10:15 |只看该作者
问题已解决。

perldoc perlretut

Grouping things and hierarchical matching
Extracting matches

这里面有详细的说明。摘抄如下:
===================================================
Extracting matches

The grouping metacharacters "()" also serve another completely differ-
ent function: they allow the extraction of the parts of a string that
matched.  This is very useful to find out what matched and for text
processing in general.  For each grouping, the part that matched inside
goes into the special variables $1, $2, etc.  They can be used just as
ordinary variables:

        # extract hours, minutes, seconds
        $time =~ /(\d\d)\d\d)\d\d)/;  # match hh:mm:ss format
        $hours = $1;
        $minutes = $2;
        $seconds = $3;

Now, we know that in scalar context, "$time =~ /(\d\d)\d\d)\d\d)/"
returns a true or false value.  In list context, however, it returns
the list of matched values "($1,$2,$3)".  So we could write the code
more compactly as

         # extract hours, minutes, seconds
         ($hours, $minutes, $second) = ($time =~ /(\d\d)\d\d)\d\d)/);

If the groupings in a regexp are nested, $1 gets the group with the
leftmost opening parenthesis, $2 the next opening parenthesis, etc.
==================================================
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP