Python查找变量关键字前后的单词,同时中间有逗号和空格

我的字符串是


string =  "Amtsgericht Berlin HRB 25665"

如何找到关键字之前和之后的单词HRB?


这样我就可以得到关键字后面的单词:


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

print(match.findall(string))


>>>>> ['25665']

如何将关键字 ( HRB) 作为变量添加到我的正则表达式中?


达令说
浏览 109回答 1
1回答

弑天下

用于(\w+)匹配单词并使用 f 字符串格式化关键字:import restring =  "Amtsgericht Berlin, HRB 25665"KEYWORD = 'HRB'match = re.compile(f'(\w+)[,|\s]*{KEYWORD}[,|\s]*(\w+)')# [('Berlin', '25665')]print(match.findall(string))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python