Home > Net >  How to match line start and ending with specific text
How to match line start and ending with specific text

Time:01-30

I'm having a hard time with this regex. I'm trying to match the amount in the line starting with "Zahlbetrag" which ends with "CHF".

The text to search is:

Zwischentotal   0,00          13,24               906,79 CHF
Zahlbetrag      0,00          13,25               906,80 CHF

My regex so far:

(?<=Zahlbetrag)(?:.*?)((\d ,\d{2})(?=([\s]*)CHF))

The result of this is currently (tested with https://regex101.com/):

Match 1:       0,00          13,25               906,80
Group 1: 906,80
Group 2: 906,80
Group 3:  

But I need the first match to be:

Match 1: 906,80

It should only include the last number, not the full line. Does anyone know how this can be accomplished?

CodePudding user response:

You can use

Zahlbetrag.*?\K\d ,\d{2}(?=\s*CHF)

See the regex demo. Details:

  • Zahlbetrag - a literal string
  • .*? - zero or more chars other than line break chars, as few as possible
  • \K - omit the text matched so far
  • \d - one or more digits
  • , - a comma
  • \d{2} - two digits
  • (?=\s*CHF) - a positive lookahead that matches a location immediately followed with zero or more whitespaces and then CHF.

CodePudding user response:

pattern = r"([\d,]*) CHF$"

st = "Zahlbetrag      0,00          13,25               906,80 CHF"

result = re.search(pattern, st)

result[1]= '906,80'
  •  Tags:  
  • Related