So I have this data array which contains math expressions as strings.
var data = ['1+1=?', '123*45?=5?088', '-5?*-1=5?', '19--45=5?', '??*??=302?', '?*11=??', '??*1=??', '??+??=??']
The question marks indicate an unknown digit, so it's part of a number. How do I split them up so that I have factors/addends, the operation, and the answer on the right side of the equation stored in an array?
This is the result that I want to get:
'1+1=?' ---> ['1', '+', '1', '?']
'123*45?=5?088' ---> ['123', '*', '45?' '5?088']
'-5?*-1=5?' ---> ['-5?', '*', '-1', 5?']
'19--45=5?' ---> ['19', '-', '-45', '5?']
'??*??=302?' ---> ['??', '*', '??', '302?']
'?*11=??' ---> ['?', '*', '11', '??']
'??*1=??' ---> ['??', '*', '1', '??']
'??+??=??' ---> ['??', '+', '??', '??']
It's tricky for me especially the one where there's a subtraction with a negative number.
Thanks in advance!
You may try this regex:
-?[\d?]+|[^=]
-?[\d?]+
: any combination of digits and ?
with an optional leading -
.|
: or[^=]
: something not a =
Check the test cases
const texts = [
'1+1=?',
'123*45?=5?088',
'-5?*-1=5?',
'19--45=5?',
'??*??=302?',
'?*11=??',
'??*1=??',
'??+??=??'
];
const regex = /-?[\d?]+|[^=]/g;
const groups = texts.map(text => text.match(regex));
console.log(groups);
If the format is consistant, you may try this regex to get each part of the equation:
(-?[\d?]+)([^=\d?])(-?[\d?]+)=(-?[\d?]+)
See the test cases
const texts = [
'1+1=?',
'123*45?=5?088',
'-5?*-1=5?',
'19--45=5?',
'??*??=302?',
'?*11=??',
'??*1=??',
'??+??=??',
'?33438-103326=410112'
];
const regex = /^(-?[\d?]+)([^=\d?])(-?[\d?]+)=(-?[\d?]+)$/;
const groups = texts.map(text => text.match(regex).splice(1));
console.log(groups);