seanlevan
seanlevan

Reputation: 1415

Regex to match a simple math equation within a string

For example, if there was this string:

what is 4+3, or, what is 3 * 2, or, what is 3x2, or, what is 4 times 2, how would this be accomplished? Is it possible to create such a matching system in regex?

Upvotes: 0

Views: 291

Answers (2)

Regular Jo
Regular Jo

Reputation: 5510

If your strings are literally What is <equation> you can do this

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

To match variable length equations (4 + 11 times 2 for example), you can do this.

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

The results you want are in capture group #1.

Upvotes: 2

m59
m59

Reputation: 43745

The following samples are all matched.

$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]);
}

A bit nicer in JavaScript. Just including this for the fun of it.

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);
});

Upvotes: 2

Related Questions