查找和连接字符串

时间:2013-11-20 12:18:45

标签: regex perl replace preg-replace

我想找一些标点字符并用空格连接它们。

例如: 如果找到任何标点符号,那么我想在它们的前面和末尾添加空格。

$line =~ s/[?%&!,.%*\[◦\]\\;@<>{}#^=\+()\$]/" $1 "/g  ;

我尝试使用Php中使用的$我们可以使用$1,但它不起作用。 我在网上搜索过,找不到Perl语法?

此外,如何将...保留为单个令牌?

我的问题的真正语法是什么。

2 个答案:

答案 0 :(得分:4)

使用此:

#!/usr/bin/perl -w
use strict; 

my $string = "For example; If i found any puncs. above list, i want to add spaces to front and end of token.";

$string =~ s/([[:punct:]])/ $1 /g;

print "$string\n";

输出:

For example ;  If i found any puncs .  above list ,  i want to add spaces to front and end of token . 
  • 显然,如果你想让你的输出与上面不同,你可以在/ /之间添加它 - 我刚用“标点符号”替换了所有标点符号。

答案 1 :(得分:3)

您需要将匹配模式与()包围,以将其捕获到$1

$line =~ s/([?%&!,.%*\[◦\]\\;@<>{}#^=\+\(\)\$])/ $1 /g;

编辑 (根据OP的评论)

  

我怎样才能保留'...'一个令牌?

一种方法是恢复该令牌的更改。

$line =~ s/ \.  \.  \. /.../g;
相关问题