用于限制字符数的正则表达式模式
Regex pattern to limit character numbers
正则表达式是 Perl 风格的。
我需要找到这些模式:<@U03AEKYL4>
它们都以相同的方式开始:<@;他们在 @ 之后都有 9 个字符(我想捕捉这些字符);它们都以 > 结尾。
This regex expression do the job: /\<@(.*?)\>/
.
But I am in trouble when it comes to this : <@U03AEKWTL|agreen>.
This expression match but I don't want it.
我无法找到限制为 9 个字符或在遇到 | 时停止的方法。
谢谢。
(?<=<\@)[^|>]{9}(?=>|\|)
尝试 this.Use 环顾四周来完成 you.See 演示的工作。
https://regex101.com/r/qH1uG3/12
@ikegami 指出不使用环视要快得多。
Rate lookaround basic
lookaround 69.9/s -- -89%
basic 644/s 821% --
尽管如此,差异很小(14 µs 对 1.6 µs),但速度越快的也越简单,因此最好。
use strict;
use warnings;
use Benchmark qw( cmpthese );
my %tests = (
lookaround => 'my ($match) = $str =~ /(?<=<\@)([^|>]{9})(?=[|>])/',
basic => 'my ($match) = $str =~ /<\@([^|>]{9})[|>]/',
);
$_ = 'use strict; use warnings; for (1..1000) { our $str; ' . $_ . ' }'
for values %tests;
local our $str = ('x' x 100) . '<@U03AEKYL4>' . ('x' x 100);
cmpthese(-3, \%tests);
怎么样:
#!/usr/bin/perl
use Modern::Perl;
my $re = qr/<\@(\w{9})>/;
while(<DATA>) {
chomp;
say /$re/ ? "OK : $_" : "KO : $_";
}
__DATA__
<@U03AEKYL4>
<@U03AEKWTL|agreen>
输出:
OK : <@U03AEKYL4>
KO : <@U03AEKWTL|agreen>
您可以根据需要在 .{9}
中更改 \w{}
。
正则表达式是 Perl 风格的。
我需要找到这些模式:<@U03AEKYL4>
它们都以相同的方式开始:<@;他们在 @ 之后都有 9 个字符(我想捕捉这些字符);它们都以 > 结尾。
This regex expression do the job:
/\<@(.*?)\>/
.But I am in trouble when it comes to this :
<@U03AEKWTL|agreen>.
This expression match but I don't want it.
我无法找到限制为 9 个字符或在遇到 | 时停止的方法。
谢谢。
(?<=<\@)[^|>]{9}(?=>|\|)
尝试 this.Use 环顾四周来完成 you.See 演示的工作。
https://regex101.com/r/qH1uG3/12
@ikegami 指出不使用环视要快得多。
Rate lookaround basic
lookaround 69.9/s -- -89%
basic 644/s 821% --
尽管如此,差异很小(14 µs 对 1.6 µs),但速度越快的也越简单,因此最好。
use strict;
use warnings;
use Benchmark qw( cmpthese );
my %tests = (
lookaround => 'my ($match) = $str =~ /(?<=<\@)([^|>]{9})(?=[|>])/',
basic => 'my ($match) = $str =~ /<\@([^|>]{9})[|>]/',
);
$_ = 'use strict; use warnings; for (1..1000) { our $str; ' . $_ . ' }'
for values %tests;
local our $str = ('x' x 100) . '<@U03AEKYL4>' . ('x' x 100);
cmpthese(-3, \%tests);
怎么样:
#!/usr/bin/perl
use Modern::Perl;
my $re = qr/<\@(\w{9})>/;
while(<DATA>) {
chomp;
say /$re/ ? "OK : $_" : "KO : $_";
}
__DATA__
<@U03AEKYL4>
<@U03AEKWTL|agreen>
输出:
OK : <@U03AEKYL4>
KO : <@U03AEKWTL|agreen>
您可以根据需要在 .{9}
中更改 \w{}
。