Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

php regex with named subpattern: get rid of an extra term in the output

Context

i’m trying to extract coefficients from a random given quadrtic equation string (via an api i don’t have a control on it) following this pattern:

ax² + bx + c = 0  # note blanc spaces are optional

obviously, b and c coefficients can be of zero value but not a, meaning bx and c terms can be optional, otherwise we are out of scope of resolving a quadratic equation.

i came up with the following regex which deals with the given pattern:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

/(?P<a>-? ?\d*)x² ?((?P<b>[+-] ?\d*)x ?)?(?P<c>[+-] ?\d+)? ?= ?0/

i used a named subpattern ?P<..> to differenciate between a, b and c coefficients, refer to this topic https://www.php.net/manual/en/function.preg-match.php section Example #4 Using named subpattern

e.g output:

array(
  0 => -2x² + 5x - 1 = 0
  a => -2
  1 => -2
  2 => + 5x  *** the extra term i'm trying to get rid of it. 
  b => + 5
  3 => + 5
  c => - 1
  4 => - 1
)

to test it online: https://www.phpliveregex.com/

Problem

it works fine as expected, but it yields an extra term, the bx term (+ 5x in the given e.g) which i’m confused and i’m trying to understand why and if it’s possible to tweak the regex to eliminate it.

>Solution :

The extra term comes from the (...)? around the named group b. You can make that a non-capturing group with the ?: prefix.

/(?P<a>-? ?\d*)x² ?(?:(?P<b>[+-] ?\d*)x ?)?(?P<c>[+-] ?\d+)? ?= ?0/
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading