Perl按特定模式[|]分割字符串问题求助
解决Perl中按多字符分隔符分割字符串的问题
嘿,我懂你遇到的这个坑!你用split /|/, $string之后得到逐字符的数组,是因为竖线|在Perl正则表达式里是**交替(OR)**的元字符——你写的/|/其实相当于匹配「空字符串 或者 空字符串」,split自然会在每个字符之间的空位置分割,把整个字符串拆成单个字符了。
你的需求是按[|]这个多字符分隔符分割,同时保留原字符串里的换行和空白字符,这时候需要把分隔符里的正则特殊字符([、|、]都是元字符)当作字面量来匹配,有两种简单的方法:
方法1:用\Q和\E标记字面量
Perl正则里的\Q和\E可以把中间的内容当作纯文本处理,自动转义所有元字符,非常适合处理这种包含特殊符号的分隔符:
my $string = "This is a comment. This is a newline. This is the end[|]This is second comment. This is second newline. [|]Last comment"; my @comments = split /\Q[|]\E/, $string; foreach my $comment (@comments) { print "Comment: '$comment'\n"; }
方法2:用quotemeta函数
quotemeta函数会把输入字符串里的所有正则元字符转义成字面量,效果和\Q\E一致:
my $delimiter = '[|]'; my @comments = split quotemeta($delimiter), $string;
运行上面的代码后,@comments数组的每个元素就会是你想要的完整注释内容,原有的换行、空格都会被保留,不会被分割。
举个输出的例子,你的测试字符串运行后会得到:
Comment: 'This is a comment. This is a newline. This is the end' Comment: 'This is second comment. This is second newline. ' Comment: 'Last comment'
完全符合你的需求~
内容的提问来源于stack exchange,提问作者cmcjake
相关产品推荐
相关产品推荐

