【问题标题】:Perl Regex unable to select word with Special character $Perl 正则表达式无法选择带有特殊字符 $ 的单词
【发布时间】:2017-05-20 12:58:13
【问题描述】:

我尝试将字符串拆分为单词(其中一个单词具有特殊字符 $),但拆分不起作用。我想把下面的字符串拆分成 "Test" "Str$ing"

$test = "Test Str$ing";

my @words = split(" ",$test);

print "@words";

print "-------1End------------\n";


foreach my $str (split /(\s)+/, $test) {        
    print "$str\n";
}

print "-------End------------\n";

我执行了上面的代码,得到了下面的结果,如你所见,第二个单词只有一半:

Test Str
-------1End------------
Test

Str
-------End------------

有什么帮助吗?

【问题讨论】:

  • 必须始终 use strictuse warnings 'all' 在您编写的每个 Perl 程序的顶部。这种措施会立即揭示问题。
  • 应该做这两件事。事实上,它不是“必须”是一个问题......

标签: regex perl


【解决方案1】:

在 Perl 中,双引号字符串中的美元符号会触发插值。所以这个作业:

$test = "Test Str$ing";

$test 设置为字符串Test Str,后跟变量$ing 的值。如果未设置$ing(并且您没有启用限制,这将导致程序此时失败),则结果只是Test Str

要获得文字美元符号,您必须使用反斜杠对其进行转义,或者改用单引号:

$test = "Test Str\$ing";
# or
$test = 'Test Str$ing';

无论如何,程序中的第一行,在#! 之后,无论如何都应该是use strict;。然后 Perl 会捕捉到这些错误并崩溃,而不是默默地让你在脚下开枪。为了更好的衡量,你也应该添加use warnings;

#!/usr/bin/env perl
use strict;
use warnings;

$test = "Test Str$ing";

观察当我尝试运行上述代码时会发生什么:

Global symbol "$test" requires explicit package name (did you forget to declare "my $test"?) at foo.pl line 5.   
Global symbol "$ing" requires explicit package name (did you forget to declare "my $ing"?) at foo.pl line 5.
Execution of foo.pl aborted due to compilation errors.

您的程序应该看起来更像这样,通过严格的更改最少:

#!/usr/bin/env perl
use strict;
use warnings;

my $test = 'Test Str$ing';

my @words = split ' ', $test;

print "@words";

print "-------1End------------\n";

foreach my $str (split /(\s)+/, $test) {
  print "$str\n";
}

print "-------End------------\n";

这对我来说仍然很奇怪,因为您在 1End 标记之前将所有单词打印在没有换行符的单行上,然后将它们中的每一个打印在中间有空行的行上(不是真正的空白,虽然 - 包含原始字符串中的空格)。但是,如果这就是您想要的,则上述方法有效。输出:

Test Str$ing-------1End------------
Test

Str$ing
-------End------------

【讨论】:

  • 感谢接受回答
【解决方案2】:

你可以用简单的引号来做:

#!/usr/bin/perl
$test = 'Test Str$ing';

my @words = split(' ',$test);

print "@words";

否则 Perl 认为$ing 是一个变量(它是空的)。

【讨论】:

  • 仍然使用单引号,我得到的结果是 Test Str
  • 那你改错了引号。 Test Str$ing 周围的人需要单身。
  • 围绕字符串!
【解决方案3】:

将数据分配给变量的最佳做法是使用单引号。 例如:

my $var_name = 'TEST MESSAGE'; 

如果由变量组成的数据要分配给另一个变量,则使用双引号。双引号中的数据将由 PERL 进行插值。 例如:

my $var1 = 'TEST';
my $var2 = "$var1 MESSAGE";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多