繁体   English   中英

如何在python中使用正则表达式提取字符串旁边的单词

[英]How to extract words next to a string using regex in python

9.DATUM DER ERTEILUNG DER ZULASSUNG/VERLÄNGERUNG DER ZULASSUNG
10.STAND DER INFORMATION
Juni 2019
Rezeptpflicht/Apothekenpflicht
Rezept- und apothekenpflichtig, wiederholte Abgabe verboten.

这是我的文本,我试图提取始终在STAND DER INFORMATION之后的日期。 Juni 2019在上面的示例文本中。

我尝试过字符串拆分方法,但这对我不起作用,因为我只需要日期。

如果您的文本在日期之前具有STAND DER INFORMATION ,如图所示,您可以使用以下内容。

代码

import re
re.findall(r'(?<=STAND DER INFORMATION\s)\D{3,4}\s\d{4}', s, re.MULTILINE)

解释

# s is text string
# <=STAND DER INFORMATION\n - look behind for STAND DER INFORMATION followed by \n
# \D is non-digit (so 3 or 4 non-digits)
# \d digits (so four digit date)
# re.MULTILINE - multiline flag to allow matches across multiple lines

测试

s = """9.DATUM DER ERTEILUNG DER ZULASSUNG/VERLÄNGERUNG DER ZULASSUNG
10.STAND DER INFORMATION
Juni 2019
Rezeptpflicht/Apothekenpflicht
Rezept- und apothekenpflichtig, wiederholte Abgabe verboten."""
dates = re.findall(r'(?<=STAND DER INFORMATION\n)\D{3,4}\s\d{4}', s, re.MULTILINE)
print(dates)

输出

['Juni 2019']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM