1

Just as the title says...i'm trying to parse a string for example

2x + 3y

and i'm trying to get only the coefficients (i.e. 2 and 3)

I first tokenized it with space character as delimiter giving me "2x" "+" "3y"

then i parsed it again to this statement to get only the coefficients

var number = eqTokens[i].match(/(\-)?\d+/);

I tried printing the output but it gave me "2,"

why is it printing like this and how do i fix it? i tried using:

number = number.replace(/[,]/, "");

but this just gives me an error that number.replace is not a function

user3580218
  • 121
  • 1
  • 13
  • note: you may be interested in [this](http://stackoverflow.com/questions/2705727/generate-syntax-tree-for-simple-math-operations). – xbug Nov 24 '14 at 04:18
  • The comma is because `number` is an array, with empty second element. In case if you used `alert` to output the value. Use `console.log` function for output into browser's console (opened by pressing F12 in most browsers) – Cheery Nov 24 '14 at 04:18
  • why is it returning an array though?? I mean shouldn't it only match the number i.e if i'm trying to match "2x" shouldn't it only return 2? – user3580218 Nov 24 '14 at 04:28

2 Answers2

1

What's wrong with this?

> "2x + 3y".match(/-?\d+(?=[A-Za-z]+)/g)
[ '2', '3' ]

The above regex would match the numbers only if it's followed by one or more alphabets.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • for decimal numbers `"-2x + 3.5y".match(/-?\d+(?:\.\d+)?(?=[A-Za-z]+)/g)` – Avinash Raj Nov 24 '14 at 04:20
  • I'm not that well-versed in the use of regex and the first thing that came up when I tried to perform this task was breaking it down as I did...Didn't know I can somehow get the number without getting the literal along with it as well – user3580218 Nov 24 '14 at 04:24
0

Match is going to return an array of every match. Since you put the optional negative in a parentheses, it's another capture group. That capture group has one term and it's optional, so it'll return an empty match in addition to your actual match.

  • Input 2x -> Your output: [2,undefined] which prints out as "2,"
  • Input -2x -> Your output: [2,-]

Remove the parentheses around the negative.

This is just for the sake of explaining why your case is breaking but personally I'd use Avinash's answer.

Gary
  • 13,303
  • 18
  • 49
  • 71