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

Select a portion if only several conditions are met in regex

I have simple equations where you don’t know where the result is located (at the end or at the beginning). Came up with this regex (code below), but it selects an equal sign as well which is expected. I can just replace the equal sign with nothing, but it’s definitely not the right way to do it. So how to select only a portion of a match?

from re import compile,findall

regex = compile(r'(\d+=)?\d+\+\d+(=\d+)?')
print(findall(regex,'1+2=3'))
#Expected: [('', '3')]
#Actual: [('', '=3')]
print(findall(regex,'3=1+2'))
#Expected: [('', '3')]
#Actual: [('', '3=')]

>Solution :

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

You can use

matches = re.findall(r'(?<==)\d+$|^\d+(?==)', text)

Or to get a single match:

match = re.search(r'(?<==)\d+$|^\d+(?==)', text)
if match:
    print(match.group())

See the regex demo. Details:

  • (?<==)\d+$ – a position immediately preceded with a =, then one or more digits are consumed and then the end of string should follow
  • | – or
  • ^\d+(?==) – start of string (^), one or more digits, and then a = must follow.
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