Home > Mobile >  Select a portion if only several conditions are met in regex
Select a portion if only several conditions are met in regex

Time:11-24

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=')]

CodePudding user response:

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.
  • Related