如果操作包含不同的变量,则不匹配

问题描述 投票:0回答:1

我想匹配使用正则表达式包含相同变量的添加。

例1

串:

5P + 3P

结果:

5P + 3P

例2

串:

失望+希伯来

结果:

失望+希伯来

例3

串:

失望+玩耍

结果:

失望+玩耍

例4:

串:

5P + 3Q

结果:

没事(根本不匹配)

我在下面创建了自己的正则表达式:

(\d+)(\w+)\+(\d+)(\w+)

但是我的正则表达式不符合上面的最后一个条件。

php regex preg-match
1个回答
0
投票

您可以将正则表达式与其他检查结合使用:

/**
 * Checks a given string operation and only returns it if it's valid.
 * 
 * @param string $operation
 * @return string|null
 */
function checkOperation(string $operation): ?string
{
  // Make sure the operation looks valid (adjust if necessary)
  if (!preg_match('/^\d+([a-zA-Z]+)\+\d+([a-zA-Z]+)$/', $operation, $matches)) {
    return null;
  }

  // Make sure the left and right variables have the same characters
  if (array_count_values(str_split($matches[1])) != array_count_values(str_split($matches[2]))) {
    return null;
  }

  return $operation;
}

但是:Kua zxsw指出

© www.soinside.com 2019 - 2024. All rights reserved.