如果操作包含不同的变量则不匹配
Don't match if the operation contain different variable
我想使用正则表达式匹配包含相同变量的加法。
示例 1
String:
5p+3p
Result:
5p+3p
示例 2
String:
5AB+3AB
Result:
5AB+3AB
示例 3
String:
5AB+3BA
Result:
5AB+3BA
例4:
String:
5p+3q
Result:
nothing (doesn't match at all)
我在下面创建了自己的正则表达式:
(\d+)(\w+)\+(\d+)(\w+)
但是我的正则表达式不满足上面的最后一个条件。
您可以将正则表达式与附加检查相结合:
/**
* 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;
}
我想使用正则表达式匹配包含相同变量的加法。
示例 1
String:
5p+3p
Result:
5p+3p
示例 2
String:
5AB+3AB
Result:
5AB+3AB
示例 3
String:
5AB+3BA
Result:
5AB+3BA
例4:
String:
5p+3q
Result:
nothing (doesn't match at all)
我在下面创建了自己的正则表达式:
(\d+)(\w+)\+(\d+)(\w+)
但是我的正则表达式不满足上面的最后一个条件。
您可以将正则表达式与附加检查相结合:
/**
* 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;
}