gpt4 book ai didi

regex - Perl 多行正则表达式匹配如何与 Unicode 字符属性交互?

转载 作者:行者123 更新时间:2023-12-02 00:18:52 24 4
gpt4 key购买 nike

我正在处理多行字符串,带有 Unix (\n) 换行符。

它的某些行的形式为“A,a”(即大写字母、逗号、空格、小写字母),我想从字符串中删除它们。

我可以用正则表达式替换来完成这个,但是有一个我不明白的谜:

使用“[A-Z]”和“[a-z]”的正则表达式在正常模式和多行模式下均有效。

使用“\p{Lu}”和“\p{Ll}”的正则表达式可以工作,但只能在正常模式下使用,不能在多行模式下使用。

这些都成功了:

$all =~ s/\n\K *[A-Z], [a-z]\n//g;    # 1

$all =~ s/^ *[A-Z], [a-z]\n//mg; # 2

$all =~ s/\n\K *\p{Lu}, \p{Ll}\n//g; # 3

但这失败了:

$all =~ s/^ *\p{Lu}, \p{Ll}\n//mg;    # 4

我希望/m 开关能改变正则表达式中“^”的含义,但除此之外别无他法。所以,我希望语句 4 能正常工作,就像语句 1、2 和 3 一样。语句 2 似乎表明多行语法没问题,而语句 3 似乎表明 Unicode 字符属性符合预期,所以,当我结合这些时,我希望语句 4 起作用。

我看过 Tom Christensen 的回答 Why does modern Perl avoid UTF-8 by default? ,但我没有看到任何关于多行正则表达式匹配的信息,也没有在其他地方找到答案。

最佳答案

我无法复制你的问题。

$ perl -wle'
$all = "foo\n A, x\nmeow";
$all =~ s/^ *[A-Z], [a-z]\n//mg;
print $all;
'
foo
meow

$ perl -wle'
$all = "foo\n A, x\nmeow";
$all =~ s/^ *\p{Lu}, \p{Ll}\n//mg;
print $all;
'
foo
meow

在 Linux 上使用 5.8.8、5.10.1、5.12.4(线程)和 5.16.0 进行了测试。

最佳猜测:pos($all) 不为零。也许你做了一些愚蠢的事情,比如 if ($all =~/.../g)


一开始我无法在删除空格的情况下重现。

$ perl -wle'
$all = "foo\nA, x\nmeow";
$all =~ s/^ *[A-Z], [a-z]\n//mg;
print $all;
'
foo
meow

$ perl -wle'
$all = "foo\n A, x\nmeow";
$all =~ s/^ *\p{Lu}, \p{Ll}\n//mg;
print $all;
'
foo
meow

在 cygwin 上使用 5.10.1(线程)进行测试。

>perl -wle"$all = qq{foo\nA, x\nmeow}; $all =~ s/^ *[A-Z], [a-z]\n//mg; print $all;"
foo
meow

>perl -wle"$all = qq{foo\nA, x\nmeow}; $all =~ s/^ *\p{Lu}, \p{Ll}\n//mg; print $all;"
foo
meow

在 Windows (ActivePerl) 上使用 5.14.0(线程)和 5.14.2(线程)进行测试。

但是,啊哈!!!!!!

>perl -wle"$all = qq{foo\nA, x\nmeow}; $all =~ s/^ *[A-Z], [a-z]\n//mg; print $all;"
foo
meow

>perl -wle"$all = qq{foo\nA, x\nmeow}; $all =~ s/^ *\p{Lu}, \p{Ll}\n//mg; print $all;"
foo
A, x
meow

在 Windows (ActivePerl) 上使用 5.10.1(线程)、5.12.1(线程)和 5.12.4(线程)进行测试。

在旧版本的 Perl 中似乎有一个错误。它似乎已在 5.14 中修复。该错误似乎在优化器中(如 -Mre=debug 所示),因此可以通过“禁用”优化器来绕过它。

>perl -wle"$all = qq{foo\nA, x\nmeow}; $all =~ s/^ *\p{Lu}, \p{Ll}\n//mg; print $all;"
foo
A, x
meow

>perl -wle"$all = qq{foo\nA, x\nmeow}; $all =~ s/^ *\p{Lu}{1}, \p{Ll}\n//mg; print $all;"
foo
meow

关于regex - Perl 多行正则表达式匹配如何与 Unicode 字符属性交互?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11786369/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com