Question

Good evening everybody.

My strings:

4x^2+1.5-x
4x^2-x+1.5
1.5+4x^2-x

I want to capture the part of those equations without a 'x' behind or another sign than +/- in front of it (1.5). I tried this regular expression:

[^\^](\d+(\.\d+)?)(?!x)

It matches the searched parts, but with a problem: The match contains the leading +/-. I thought I can solve this with a lookbehind, but since I work with the C++11 library with ECMAScript, this is not supported.

Does somebody know how to solve this?

Thank you :)

Was it helpful?

Solution

rewritten based on even more comments.

Okay, based on the additional criteria and clarification provided in your comments:

  • extract numbers without a 'x^n' behind them.
  • they can appear everywhere, at the begin, in the middle or at the end
  • they can(!) have a '+'/'-' in front of them. if it is a '+', this should not get captured but a '-' should. (clarified:need to capture both, just only SHOW -)
  • after these numbers, there can be a '+' or '-', too (rare case, but needs to be noticed).
  • (reiterated: can't use negative lookbehinds)

(?:[-+]|^)[0-9.]+(?=[-+]|$)

This will match for the following (there's no good way to format and highlight on here so I wrapped the matches in []):

4x^2[+8.15]-x
4x^2-x[+1.25]
[1.9]+4x^2-x
[3]+2x^4-x
x[-6]
[.7]+3x
[-.75]+3x
4x[-0.5]
4x[+0.8]
77x
9.8x
-2.52x^3-4x^2[+1.45]
4x^2[+8.15][-1.5]

you will need to strip leading +

Array
(
    [0] => Array
        (
            [0] => +8.15
            [1] => +1.25
            [2] => 1.9
            [3] => 3
            [4] => -6
            [5] => .7
            [6] => -.75
            [7] => -0.5
            [8] => +0.8
            [9] => +1.45
            [10] => +8.15
            [11] => -1.5
        )
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top