如何为“:”之后的所有文本编写正则表达式

2024-10-17 08:19:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要过滤句子,从整个句子中只选择几个词

例如,我有示例文本:

ID: a9000006        
NSF Org     : DMI
Total Amt.  : $225024

Abstract    :This SBIR proposal is aimed at (1) the synthesis of new ferroelectric liquid crystals with ultra-high polarization,                    
             chemical stability and low viscosity
token = re.compile('a90[0-9][0-9][0-9][0-9][0-9]| [$][\d]+ |')
re.findall(token, filetext)

我得到了'a9000006','$225024',但是我不知道如何为紧跟在"NSF Org:"之后的三个大写字母编写regex,也就是"DMI""Abstract:"之后的所有文本


Tags: org文本reabstracttokenid示例this
2条回答

这一定行。你知道吗

: .*

你可以在这里查这个。 check

如果您想创建一个正则表达式来匹配这4个字段中的每一个,并对每个字段进行显式检查,那么请使用this regex:\s?(a90[\d]+|[$][\d]+|[A-Z]{3}|.*$)

>>> token = re.compile(r':\s?(a90[\d]+|[$][\d]+|[A-Z]{3}|.*$)', re.DOTALL)  # flag needed
>>> re.findall(token, filetext)
['a9000006', 'DMI', '$225024', 'This SBIR proposal is aimed at (1) the synthesis of new ferroelectric liquid crystals wi
th ultra-high polarization,                    \n             chemical stability and low viscosity']
>>> 

但是,由于您同时搜索所有,因此最好使用一个将所有4个匹配在一起并进行泛型匹配的方法,例如this answer here中的方法。你知道吗

相关问题 更多 >