regex - Perl - 匹配双引号文本的正则表达式

标签 regex string perl hash double-quotes

请在正则表达式匹配方面需要一些帮助。我正在尝试匹配一个双引号文本字符串,在一个大字符串中,它本身可以包含成对的双引号!这是一个例子:

"Please can ""you"" match this"

下面显示了我的问题的更完整示例以及到目前为止我所遇到的问题。下面的代码仅在散列中正确存储了“paris”,由于双引号对提前终止了长描述,因此 london 和 melbourne 都不正确。

非常感谢任何帮助。

use strict;
use warnings;
use Data::Dumper;

my %hash;

my $delimiter = '/begin CITY';
local $/ = $delimiter;

my $top_of_file = <DATA>;
my $records=0;

while(<DATA>) {

   my ($section_body) = m{^(.+)/end CITY}ms;

   $section_body =~ s{/\*.*?\*/}{}gs;     # Remove any comments in string

   $section_body =~ m{  ^\s+(.+?)   ## Variable name is never whitespace seperated
                                    ## Always underscored.  Akin to C variable names

                        \s+(".*?")  ## The long description can itself contain
                                    ## pairs of double quotes ""like this""

                        \s+(.+)     ## Everything from here can be split on
                                    ## whitespace

                        \s+$
                     }msx;

   $hash{$records}{name} = $1;
   $hash{$records}{description} = $2;

   my (@data) = split ' ', $3;

   @{ $hash{$records} }{qw/ size currency /} = @data;

   ++$records;
}

print Dumper(\%hash);


__DATA__
Some header information

/begin CITY

    london  /* city name */
    "This is a ""difficult"" string to regex"
    big
    Sterling

/end CITY

/begin CITY paris
         "This is a simple comment to grab."
         big
         euro  /* the address */
/end CITY


/begin CITY

    Melbourne
    "Another ""hard"" long description to 'match'."
    big
    Dollar

/end CITY

最佳答案

改变这个:

".*?"

为此:

"(?>(?:[^"]+|"")*)"

此外,您使用非贪婪匹配也不是很安全。像这样:

\s+(.+?)   ## Variable name is never whitespace seperated
           ## Always underscored.  Akin to C variable names

很可能会在变量名中包含空格,如果 Perl 发现那是唯一的匹配方式。 (它将更喜欢在包含空格之前停止,但它不做任何保证。)

而且您应该始终检查以确保 m{} 找到了一些东西。如果您确定它总是匹配,那么您可以添加一个or die 来验证这一点。

关于regex - Perl - 匹配双引号文本的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9592039/

相关文章:

perl - 简单的 perl 添加程序出错了吗?

javascript - 在 javascript 中使用正则表达式在单词两侧添加空格

javascript - 使用 JavaScript 排除正则表达式行首或行尾的匹配项

c++ - 正则表达式有效和无效在一起

Linux shell 脚本 - 获取字符串中数字的总和,但同时将字符串与总和保持一致

使用多个选项通过匹配字符串来替换字符

regex - Mercurial .hgignore 沮丧

java - 使用数组、列表还是数千个字符串?

xml - Perl,XML::Twig,如何读取具有相同标签的字段

mysql - 我是否需要为 DBIx::Class belongs_to 关系手动创建索引