1

I suck at regex and I've been trying to get through this problem. The problem is that I have a string and I want to match any "+" or "-" that aren't preceded by a "^".

Example string:

100x^-3+2x-10

The string above would be mathematically formatted or read as "one hundred times x to the -3 power, plus two times x, minus ten".

And I want to match the "+" before "2x" and the "-" before the "10" but not the "-" after "100x^". I hope it's not that confusing. I have tried the following reg, with no luck:

[^\^][\+|\-]

Obviously I'm missing a big detail somewhere.

TylerH
  • 20,799
  • 66
  • 75
  • 101
user1549913
  • 67
  • 1
  • 10
  • Are you trying to match all the text after the operator or just trying to test if the string contains a plus or minus not preceded by a caret. – Asad Saeeduddin Mar 17 '13 at 00:01

4 Answers4

0

You could use the old trick of simulating look behind by reversing the string, then matching against /[\+\-](?!=\^)/.

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
0

It runs ok in chrome console, anyway you can try with : "100x^-3+2x-10".match(/[^\^$]([\-|\+])/ig) , I advice you to test your regex in the console of Google Chrome.

Daniel Flores
  • 770
  • 3
  • 12
  • 31
0

If you need to split by + or - :

"100x^-3+2x-10".replace(/([^^])[-+]/g,'$1@').split('@')
Output: ["100x^-3", "2x", "10"]

I used @ as a temp char (but you can use a unique set of chars) to mark the signs not prefixed by ^ then safely split by the chosen temp char.

CSᵠ
  • 10,049
  • 9
  • 41
  • 64
0

Give this a shot:

/(?<!\^)[+-]/
woemler
  • 7,089
  • 7
  • 48
  • 67
  • im posting this comment just incase somebody finds this question useful, i had said this worked (the reg you gave) because i tried it in RegExr app, although I just tried in my script with match and i got the following error: "Uncaught SyntaxError: Invalid regular expression: /(?<!\^)[+-]/: Invalid group", i don't know why the script can't make it work but my reg testing app does, oh well thanks anyway! – user1549913 Mar 17 '13 at 04:17
  • 1
    My appologies, it looks like Javascript does not support look-behinds: http://stackoverflow.com/questions/5973669/javascript-regexp-lookbehind-assertion-is-causing-a-invalid-group-error – woemler Mar 17 '13 at 18:38