简体   繁体   中英

JavaScript - Matching alphanumeric patterns with RegExp

I'm new to RegExp and to JS in general (Coming from Python), so this might be an easy question: I'm trying to code an algebraic calculator in Javascript that receives an algebraic equation as a string, eg,

string = 'x^2 + 30x -12 = 4x^2 - 12x + 30';

The algorithm is already able to break the string in a single list, with all values on the right side multiplied by -1 so I can equate it all to 0, however, one of the steps to solve the equation involves creating a hashtable/dictionary, having the variable as key. The string above results in a list eq :

eq = ['x^2', '+30x', '-12', '-4x^2', '+12x', '-30'];

I'm currently planning on iterating through this list, and using RegExp to identify both variables and the respective multiplier, so I can create a hashTable/Dictionary that will allow me to simplify the equation, such as this one:

hashTable = {
    'x^2': [1, -4],
    'x': [30, 12],
    ' ': [-12]
}

I plan on using some kind of for loop to iter through the array, and applying a match on each string to get the values I need, but I'm quite frankly, stumped. I have already used RegExp to separate the string into the individual parts of the equation and to remove eventual spaces, but I can't imagine a way to separate -4 from x^2 in '-4x^2' .

You can try this (-?\\d+)x\\^\\d+ .

When you execute match function :

var res = "-4x^2".match(/(-?\d+)x\^\d+/)

You will get res as an array : [ "-4x^2", "-4" ] You have your '-4' in res[1].

By adding another group on the second \\d+ (numeric char), you can retrieve the x power.

var res = "-4x^2".match(/(-?\d+)x\^(\d+)/) //res = [ "-4x^2", "-4", "2" ]

Hope it helps

If you know that the LHS of the hashtable is going to be at the end of the string. Lets say '4x', x is at the end or '-4x^2' where x^2 is at end, then we can get the number of the expression:

var exp = '-4x^2'
exp.split('x^2')[0] // will return -4

I hope this is what you were looking for.

function splitTerm(term) {
    var regex = /([+-]?)([0-9]*)?([a-z](\^[0-9]+)?)?/
    var match = regex.exec(term);
    return {
        constant: parseInt((match[1] || '') + (match[2] || 1)),
        variable: match[3]
    }
}

splitTerm('x^2');  // => {constant:   1, variable: "x^2"}
splitTerm('+30x'); // => {constant:  30, variable: "x"}
splitTerm('-12');  // => {constant: -12, variable: undefined}

Additionally, these tool may help you analyze and understand regular expressions:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM