在Perl中用括号替换句子的问题

时间:2013-04-01 05:30:39

标签: perl

我有一个句子需要在某些修改后更换。

但是,该句子不会替换我的原始文件,因为它包含圆括号。我如何确保它替换,因为在句子中并不总是需要圆括号的存在。

例如。 $table=~s/<table-wrap-foot>($foot1)<\/table-wrap-foot>/$foot/sg; 这里,$ foot可能有也可能没有圆括号。我甚至尝试使用\Q$foot\E,但它无法正常工作。!!

任何帮助将不胜感激

5 个答案:

答案 0 :(得分:2)

尝试通过正则表达式对任意输入执行此操作将导致疯狂。使用XML::Twig

#!/usr/bin/env perl

use 5.012;
use strict;
use warnings;

use XML::Twig;

my $xml = <<EO_XML;
<table-wrap-foot>
translocations or inversions: t(8;21), inv(16) or
t(16;16), t(15;17), t(9;11), t(v;11)(v;q23),
t(6;9), inv(3) or t(3;3)
</table-wrap-foot>
EO_XML

my $t = XML::Twig->new;
$t->parse($xml);

say $t->root->first_child_text;

答案 1 :(得分:1)

在正则表达式中,()是特殊字符(用于分组)。要按照字面意思匹配它们,请将其转义为\(\)

要选择匹配某些内容,请使用?量词。

所以你的正则表达式变成:

$table=~s/<table-wrap-foot>\(?$foot1\)?<\/table-wrap-foot>/$foot/sg;

或者使用扩展语法,以获得更多可读性:

$table =~ s{
  <table-wrap-foot>      # beginning marker
  \(?                    # optional opening paren
  $foot1                 # the original sentence
  \)?                    # optional clonsing paren
  </table-wrap-foot>     # closing marker
}{$foot}xsg;

请注意,正则表达式末尾的x表示您可以在表达式中使用注释,并忽略普通空格(使用\s[ ]来匹配它)。此外,如果您使用s{}{}作为分隔符,则无需再转义结束标记中的/

更多信息perldoc perlop : Regexp Quote-Like Operators

答案 2 :(得分:1)

如果你想在你的搜索值中有parens,你需要逃避逃脱paren的反斜杠。替换中的括号不会成为问题,但它将在匹配中,因为它们用于正则表达式中的分组。

假设您有一个分配给$table的值,您只想传递要搜索和替换的文本。

以下示例将(hello)替换为字符串hi中的<table-wrap-foot>(hello)</table-wrap-foot>

#!/usr/bin/perl

$foot = "(hello)";
print $foot . "\n";                     # $foot = (hello)
# replace all ( and ) with \( and \)
$foot =~ s/(\(|\))/\\$1/sg;             # $foot = \(hello\)
print $foot . "\n";

# replace with "hi"
$table = "<table-wrap-foot>(hello)</table-wrap-foot>";
print $table . "\n";
$table =~ s/<table-wrap-foot>($foot)</table-wrap-foot>/hi/sg;
print $table;

输出:

> perl test.pl 
(hello)
\(hello\)
<table-wrap-foot>(hello)</table-wrap-foot>
hi

答案 3 :(得分:0)

试试这个:

$table=~s/<table-wrap-foot>[\(]*$foot1[\)]*<\/table-wrap-foot>/$foot/sg;

这样你就可以将括号视为普通字符,并要求它们有0或1个巧合。

答案 4 :(得分:-1)

无法找到出路......所以诀窍...... 在开始操作文件之前用自制实体替换了parantheses,然后在将结果打印到文件之前将其替换为相同的文件...

相关问题