用于匹配字符串中简单数学方程式的正则表达式

Regex to match a simple math equation within a string

例如,如果有这个字符串:

what is 4+3,或者,what is 3 * 2,或者,what is 3x2,或者,what is 4 times 2,如何实现呢?是否可以在正则表达式中创建这样的匹配系统?

以下样本全部匹配。

$samples = Array(
  'what is 4+3',
  'what is 2 plus 7',
  'what is 3 * 2',
  'what is 3x2',
  'what is 4 times 2'
);

foreach($samples as $sample) {
  $sample = preg_replace('/(times)|\*/', 'x', $sample);
  $sample = str_replace('plus', '+', $sample);
  preg_match('/what is \d ?[+x] ?\d/', $sample, $matches);
  var_dump($matches[0]);
}

JavaScript 更好一些。包括这个只是为了好玩。

var samples = [
  'what is 4+3',
  'what is 2 plus 7',
  'what is 3 * 2',
  'what is 3x2',
  'what is 4 times 2'
];

samples.forEach(function(sample) {
  sample = sample
    .replace(/(times)|\*/, 'x')
    .replace('plus', '+')
  ;
  var match = sample.match(/what is \d ?[+x] ?\d/);
  console.log(match);
});

如果你的字符串是字面上的 What is <equation> 你可以这样做

What is (\d+ ?([^\s] ?\d+ ?))

要匹配可变长度方程(例如4 + 11 times 2),您可以这样做。

What is (\d+ ?([^\s] ?\d+ ?)+)

您想要的结果在捕获组 #1 中。