0

I am trying to implement a parser for systems of linear equations, so I want to match strings of the form:

2x + 3y = 5
55x + 34s + 9872v = 25

So, my regular expression is as follows:

/([0-9]+[a-z]\+{0,1})*=[0-9]+/;

However, it is matching incorrect expressions, such as:

23x + 50 = 35
36x + 5xg = 10

And I don't understand why, from what I can understand, it should only be a single digit (of any length) followed immediately by a single character, representing variable.

3
  • The pattern does not match anything there at all ATM due to the spaces. Commented Nov 18, 2019 at 6:06
  • May we ask what the ultimate goal here is? I mean, is all you want is to verify an expression, or do you, for example, want to extract components? Commented Nov 18, 2019 at 6:06
  • at present, I just want to match the entire pattern Commented Nov 18, 2019 at 6:20

2 Answers 2

3

Try below regex. Demo is here

(\d*(?<![a-z])[a-z][+-]?)+=\-?\d+
Sign up to request clarification or add additional context in comments.

Comments

0

You need to match the entire text, but the regex is returning any matching segment.

Modify your expression to /^([0-9]+[a-z]\+{0,1})*=[0-9]+$/, here the ^ and $ symbols are added to match entire string.

console.log("2x+3y=5".match(/^([0-9]+[a-z]\+{0,1})*=[0-9]+$/));
console.log("55x+34s+9872v=25".match(/^([0-9]+[a-z]\+{0,1})*=[0-9]+$/));
console.log("23x+50=35".match(/^([0-9]+[a-z]\+{0,1})*=[0-9]+$/));
console.log("36x+5xg=10".match(/^([0-9]+[a-z]\+{0,1})*=[0-9]+$/));

2 Comments

I inputted 5x+5=5 into my program and it matched, when it shouldn't as there is no variable attached to the second number.
@Perplexityy @Mahbub Moon x+2y=3 not matching and it's not working for -ve cases

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.