用于检查所有字符串是否为整数并拆分为单个整数的 REGEX 验证模式

REGEX Pattern for Validation that check all string is integer and split into single integers

我尝试了多次来制作一个可以验证给定字符串是否为自然数并将其拆分为单个数字的模式。

..并且缺乏对正则表达式的理解,我能想到的最接近的是..

^([1-9])([0-9])*$^([1-9])([0-9])([0-9])*$ 类似的东西...

它只生成第一个、最后一个和第二个或最后一个第二个拆分号码。

我想知道我需要知道什么才能解决这个问题..谢谢

您可以使用像

这样的两步解决方案
if (preg_match('~\A\d+\z~', $s)) { // if a string is all digits
    print_r(str_split($s));         // Split it into chars
}

看到一个PHP demo

一步正则表达式解决方案:

(?:\G(?!\A)|\A(?=\d+\z))\d

regex demo

详情

  • (?:\G(?!\A)|\A(?=\d+\z)) - 上一个匹配项的结尾 (\G(?!\A)) 或 (|) 字符串的开头 (^) 后跟 1 或到字符串末尾的更多数字 ((?=\d+\z))
  • \d - 一个数字。

PHP demo:

$re = '/(?:\G(?!\A)|\A(?=\d+\z))\d/';
$str = '1234567890';
if (preg_match_all($re, $str, $matches)) {
    print_r($matches[0]);
}

输出:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 0
)