简体   繁体   中英

Don't match if the operation contain different variable

I want to match an addition which contain same variable using regex.

Example 1

String:

5p+3p

Result:

5p+3p

Example 2

String:

5AB+3AB

Result:

5AB+3AB

Example 3

String:

5AB+3BA

Result:

5AB+3BA

Example 4:

String:

5p+3q

Result:

nothing (doesn't match at all)

I have created my own regex below:

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

However my regex doesn't fulfill the last condition above.

You could combine a regex with an additional check:

/**
 * 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;
}

Demo: https://3v4l.org/iS8Ih

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM