我可以将这两个正则表达式合二为一吗?

Ste*_*sky 1 regex perl

我的应用程序的数据库记录有十位数的ID,空值可以用""或表示"0000000000".目前,我使用以下习惯来检查有效ID:

my $is_valid = $id =~ m/[0-9]{10}/ && $id =~ /[1-9]/;
Run Code Online (Sandbox Code Playgroud)

第一个正则表达式检查整体格式,第二个正则表达式"0000000000"通过查找字符串中某处的非空数字来排除该 值.我很好奇我是否可以将这两个正则表达式合二为一.

那个正则表达式的效率可能会低一些,但正如我所说,我只是好奇它是否可行.

Tim*_*ker 5

这需要一个先行断言(为了清晰起见,将正则表达式分解为多行):

if ($id =~ 
    m/\A      # Anchor the match to the start of the string
    (?!0*\z)  # Assert that it's impossible to match only zeroes until end-of-str
    [0-9]{10} # Match exactly 10 digits
    \z        # Anchor the match to the end of the string
    /x)       # (verbose regex)
    {
    # Successful match
}
Run Code Online (Sandbox Code Playgroud)