Signal - 2 years ago 62
Python Question

# How to make a "Regular Expression Template" that gets values in between certain places. Python 3

I am inquiring about how to make something similar to a Python Template in reverse, using regular expressions. A template for a quadratic would look something like this:

("\${a}x^2+\${b}x+\${c}")

How can one reverse this to make it instead take a string and pull out a, b, c.

The reason behind this question is I was recently trying to perform the task to get a and b like this:

``````    a = []
for character in self.text:
if re.search("\d", character):
a.append(character)
else:
break
b = re.search('%s(.*)%s' % ("\d*[\w][\^]2[+-]", "\w[+-]"), self.text).group(1)

return a, b
``````

It works fine but it's not very pythonic and it's very cumbersome. I'm sure there's a better way.

Here's a possible start on what I think you're asking for -- it uses regular expressions to tease out the quadratic constants:

``````import re

EXAMPLES = [
"6x^2",
"5x",
"4",
"x^2 - 3x - 4",
"6x^2 + 11x - 35",
"x^2 - 7x",
"2x^2 + 5x + 3",
"5x - 3",
"x^2 - 3",
]

QUADRATIC_PATTERN = r"(?:(\d*)[a-z]\^2)?" r"(?:\s*[-+]\s*)?" r"(?:(\d*)[a-z])?" r"(?:\s*[-+]\s*)?" r"(\d*)?"

for equation in EXAMPLES:

if (matchobj):
print(equation, ": a =", matchobj.group(1), "b =", matchobj.group(2), "c =", matchobj.group(3))
else:
``````

The `QUADRATIC_PATTERN` is defined as a series of raw strings that Python will concatenate into one string -- this just made it easier to develop and debug. See `re.VERBOSE` for a different/better way to do this.

The above produces:

``````6x^2 : a = 6 b = None c =
5x : a = None b = 5 c =
4 : a = None b = None c = 4
x^2 - 3x - 4 : a =  b = 3 c = 4
6x^2 + 11x - 35 : a = 6 b = 11 c = 35
x^2 - 7x : a =  b = 7 c =
2x^2 + 5x + 3 : a = 2 b = 5 c = 3
5x - 3 : a = None b = 5 c = 3
x^2 - 3 : a =  b = None c = 3
``````

Where `None` means the term wasn't present and an empty result means the term was present but no constant was given.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download