首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在使用Perl的RE中使用换行符替换s/?

如何在使用Perl的RE中使用换行符替换s/?
EN

Stack Overflow用户
提问于 2014-12-17 16:38:02
回答 2查看 81关注 0票数 0

输入文件包含超过1个换行符,空标记如下:

代码语言:javascript
复制
<html>
<body>
<title>XXX</title>
<p>text...</p>
<collaboration seq="">
<ce:text></ce:text>
</collaboration>
...


<p>text</p>
<collaboration seq="">
<ce:text>AAA</ce:text>
</collaboration>
<p>text</p>
</body>
</html>

输出文件只需要一个换行符,必须删除空标签

代码语言:javascript
复制
<html>
<body>
<title>XXX</title>
<p>text...</p>
...
<p>text</p>  
<p>text</p>
<collaboration seq="">
<ce:text>AAA</ce:text>
</collaboration>
</body>
</html>

在尝试过的代码中:

代码语言:javascript
复制
print "Enter the file name without extension: ";
chomp($filename=<STDIN>);
open(RED,"$filename.txt") || die "Could not open TXT file";
open(WRIT,">$filename.html");
while(<RED>)
{
  #process in file
  s/<collaboration seq="">\n<ce:text><\/ce:text>\n<\/collaboration>//g;
  s/\n\n//g;
  print WRIT $_;
}
close(RED);
close(WRIT);

上面的代码不会清除任何需要的东西。如何解决这个问题?

EN

回答 2

Stack Overflow用户

发布于 2014-12-17 21:36:19

首先,您应该实际使用该文件。因此,假设您使用zigdon's method

代码语言:javascript
复制
my $file;
{
    print "Enter the file name without extension: ";
    my $filename = <STDIN>

    chomp($filename);
    open F, $filename or die "Can't read $filename: $!";
    local $/;  # enable slurp mode, locally.
    $file = <F>;
    close F;
}

现在,$file包含了文件的内容,因此您可以使用它。

代码语言:javascript
复制
#process in file
$file ~= s/<collaboration seq="">\R<ce:text><\/ce:text>\R<\/collaboration>//g;
$file ~= s/\R{2,}/\n/g; #I'm guessing this is probably what you intended
print WRIT $file;    
票数 0
EN

Stack Overflow用户

发布于 2014-12-20 12:19:16

您可以使用XML::Simple实现这一点:

代码语言:javascript
复制
# use XML simple to process the XML
my $xs = XML::Simple->new(
      # remove extra whitespace
      NormaliseSpace => 2,
      # keep root element
      KeepRoot       => 1,
      # force elements to arrays
      ForceArray     => 1,
      # ignore empty elements
      SuppressEmpty  => 1
);
# read in the XML
my $ref = $xs->XMLin($xml);


# print out the XML minus the empty tags
print $xs->XMLout($ref);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27521313

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档