-2

My string is

string =  "Amtsgericht Berlin HRB 25665"

How can I find the word before AND after the keyword HRB?

This way I get the word after my keyword:

match = re.compile(r'HRB\s+((?:\w+(?:\s+|$)){1})')
print(match.findall(string))

>>>>> ['25665']

How can I add the keyword (HRB) as a variable into my regex expression?

Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22
PParker
  • 1,419
  • 2
  • 10
  • 25

1 Answers1

0

Use (\w+) to match words and format the keyword using f-string:

import re


string =  "Amtsgericht Berlin, HRB 25665"

KEYWORD = 'HRB'

match = re.compile(f'(\w+)[,|\s]*{KEYWORD}[,|\s]*(\w+)')

# [('Berlin', '25665')]
print(match.findall(string))

Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22