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

时间:2015-03-01 02:44:53

标签: php regex matching

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

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

2 个答案:

答案 0 :(得分: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);
});

答案 1 :(得分:2)

如果您的字符串字面上What is <equation>,则可以执行此操作

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

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

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

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