正则表达式匹配带有符号的字母和数字

regex matching letters and digits with signs

对于PHP的preg_match,我尝试将元素符号匹配为

我想出了一个正则表达式

preg_match('/^[A-Za-z](\d[+|-])/', $str, $match);

但不匹配 K+。我怎样才能将 OR 条件也添加到数字?

您可以匹配一个大写字母跟在可选的小写字母后面,表示以数字或 [-+] 符号或两者结尾的元素名称,使用:

([A-Z][a-z]*)(\d*[-+]?)

RegEx live demo

PHP 代码(参见演示 here):

preg_match_all('~([A-Z][a-z]*)(\d*[-+]?)~', $str, $matches);

所提供输入的输出:

Array
(
    [0] => Array
        (
            [0] => K+
            [1] => K
            [2] => +
        )

    [1] => Array
        (
            [0] => Cr7+
            [1] => Cr
            [2] => 7+
        )

    [2] => Array
        (
            [0] => O2-
            [1] => O
            [2] => 2-
        )

)