javascriptregexmatching

How do I match components in a string math expression with unknown digits in javascript?


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!


Solution

  • You may try this regex:

    -?[\d?]+|[^=]
    

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


    Edit

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