【问题标题】:Recursively extract strings between quotes in a given string递归提取给定字符串中引号之间的字符串
【发布时间】:2023-03-06 05:57:01
【问题描述】:

给定一个带有引号内子字符串的字符串,提取所有这样的子字符串

我已经编写了以下代码,但有些东西告诉我它很丑(尽管它似乎确实可以解决问题)

my $str = 'printf ("hellp;world", and "this is ; also" and )';

loop:
if ($str =~ /"(.*?)"/) {
    my $substr = $1;
    $str =~ s/"$substr"//;
    print "$substr\n";
}
if ($str =~ /"/) {
    goto loop;
}
perl quotes.pl
hellp;world
this is ; also

所以它确实按预期工作。

【问题讨论】:

  • 子字符串可以转义引号吗?例如。 'printf( "hello \"peter\"", ... )'

标签: string perl extract quotes


【解决方案1】:

您可以通过在任一标量上下文中使用 /g 正则表达式标志直接执行此操作:

while ($str =~ /"([^"]*)"/g) {
    print "$1\n";
}

...或列表上下文:

for my $match ($str =~ /"([^"]*)"/g) {
    print "$match\n";
}

我还将.*? 更改为[^"]*,因为最好具体说明您要匹配的内容。

/g 记录在perldoc perlop

/g 修饰符指定全局模式匹配——即在字符串中匹配尽可能多的次数。它的行为方式取决于上下文。 在列表上下文中,它返回一个由正则表达式中任何捕获括号匹配的子字符串的列表。 如果没有括号,它返回一个所有匹配字符串的列表,就好像周围有括号一样整个模式。

在标量上下文中,m//g 的每次执行都会找到下一个匹配项,如果匹配则返回 true,如果没有进一步匹配则返回 false。 可以读取最后一次匹配后的位置或使用pos() 函数设置;见"pos" in perlfunc。失败的匹配通常会将搜索位置重置为字符串的开头,但您可以通过添加 /c 修饰符来避免这种情况(例如,m//gc)。修改目标字符串也会重置搜索位置。

(强调我的。)

【讨论】:

    猜你喜欢
    • 2011-01-05
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 2021-12-15
    • 2012-09-05
    • 1970-01-01
    相关资源
    最近更新 更多