正则表达式匹配字母和数字与标志

时间:2018-05-19 13:35:42

标签: regex preg-match

使用PHP的preg_match,我尝试将元素符号匹配为

  • K + => array( [0] => K+, [1] => K, [2] => +)

  • Cr7 + => array( [0] => Cr7+, [1] => Cr, [2] => 7+)

  • O2- => array( [0] => O2-, [1] => O, [2] => 2-)

我提出了

的正则表达式
preg_match('/^[A-Za-z](\d[+|-])/', $str, $match);

但它与K+不匹配。如何在数字中添加OR条件?

1 个答案:

答案 0 :(得分:1)

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

([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-
        )

)