Skip to main content
 首页 » 编程设计

python之正则表达式类似于 Python 中的赫斯特模式

2024年09月03日24lidabo

我正试图想出一个类似于 ones listed here 的正则表达式赫斯特模式以获得以下结果:

NP_The_Eleventh_Air_Force is NP_a_Numbered_Air_Force of NP_the_United_States_Air_Force_Pacific_Air_Forces (NP_PACAF). 
NP_The_Eleventh_Air_Force (NP_11_AF) is NP_a_Numbered_Air_Force of NP_the_United_States_Air_Force_Pacific_Air_Forces (NP_PACAF). 

为每个句子做 re.search(regex, sentence) 我想匹配这 2 个组NP_The_Eleventh_Air_Force NP_a_Numbered_Air_Force

这是我的尝试,但没有得到任何匹配项:

(NP_\\w+ (, )?is (NP_\\w+ ?)) 

请您参考如下方法:

在这两个句子中,我认为 (, )? 不存在,但是括号之间的部分是这样你可以使该部分成为可选的。

同时将最后一个括号从 )) 移动到 (NP_\w+) 以创建第一个组。

包括可选逗号和空格的模式可以是:

(NP_\w+)(?: \([^()]+\))? (?:, )?is (NP_\w+ ?) 

Regex demo

如果你不需要末尾的空格并且逗号空格不存在,你的模式可以是:

(NP_\w+)(?: \([^()]+\))? is (NP_\w+) 
  • (NP_\w+) 捕获组 1 匹配 NP_ 和 1+ 个单词字符
  • (?:\([^()]+\))? 可选匹配空格和带括号的部分
  • 是字面匹配
  • (NP_\w+) 捕获组 2 匹配 NP_ 和 1+ 个单词字符

查看 regex demo | Python demo

例如

import re 
 
regex = r"(NP_\w+)(?: \([^()]+\))? is (NP_\w+)" 
test_str = "NP_The_Eleventh_Air_Force is NP_a_Numbered_Air_Force of NP_the_United_States_Air_Force_Pacific_Air_Forces (NP_PACAF)." 
matches = re.search(regex, test_str) 
 
if matches: 
    print(matches.group(1)) 
    print(matches.group(2)) 

输出

NP_The_Eleventh_Air_Force 
NP_a_Numbered_Air_Force