首页 > 解决方案 > 如何只匹配几个数字?

问题描述

目前,我有一个问题只能匹配几个数字。

例如:

my $input1 = "1234 abc test";     - > expect - match and return 1234
my $input2 = " 1234 abc test";    - > expect - match and return 1234
my $input3 = "abc test 1234";     - > expect - match and return 1234
my $input4 = "a1234 test";         not match
my $input5 = "1234- abc test";     not match
my $input6 = "abc 12345 test";     not match

对于以上 6 个示例,只有 input1、input2 和 input3 需要 return 1234。其他人将返回not matched。如何编写这样的正则表达式?

我尝试这样做,但它不适用于 input1 和 input3。

if $input =~ /\s+(\d{4,4})\s+/{

}

标签: perl

解决方案


/(?:^|\s)(\d{4})(?:\z|\s)/a

或者

/(?<!\S)(\d{4})(?!\S)/a   # Not proceeded by a non-space and not followed by a non-space.

\d通常匹配 630 个不同的代码点。/a导致它只匹配[0-9]。)


推荐阅读