我正在寻找与以下字符串匹配的正则表达式模式:
一些示例文本(SET)演示了我正在寻找的内容。能源系统模型(ESM)用于寻找特定的最佳值(SCO)。有人说计算机系统(CUST)很酷。夏天应该首选户外比赛(OUTS)。
我的目标是匹配以下内容:
Some example text (SET)
Energy system models (ESM)
specific optima (SCO)
computer systems (CUST)
outside (OUTS)
重要的是,它并不总是恰好三个单词及其第一个字母。有时用于缩写的字母仅包含在前面的单词中。这就是为什么我开始研究positive lookbehind
。然而,它受到长度的限制,可以通过将其与positive lookahead
。到目前为止,我还无法想出一个可靠的解决方案。
到目前为止我尝试过的:
(\b[\w -]+?)\((([A-Z])(?<=(?=.*?\3))(?:[A-Z]){1,4})\)
这工作得很好,但匹配项包含太多单词:
Some example text (SET)
Energy system models (ESM)
are used to find specific optima (SCO)
Some say Computer systems (CUST)
In the summer playing outside (OUTS)
我还尝试在第一组的开头使用缩写的第一个字母的引用。但这根本不起作用。
我看过但没有发现有用的东西:
- 用于捕获缩写的正则表达式 https://stackoverflow.com/questions/60658473/regex-for-catching-abbreviations
- 使用 Python 正则表达式匹配首字母缩略词及其含义 https://stackoverflow.com/questions/40622523/match-acronym-and-their-meaning-with-python-regex
有用的资源:
- 向后看的东西 https://stackoverflow.com/questions/3796436/whats-the-technical-reason-for-lookbehind-assertion-must-be-fixed-length-in-r
- 一般来说,关于环视的东西 https://www.rexegg.com/regex-lookarounds.html
我建议使用
import re
def contains_abbrev(abbrev, text):
text = text.lower()
if not abbrev.isupper():
return False
cnt = 0
for c in abbrev.lower():
if text.find(c) > -1:
text = text[text.find(c):]
cnt += 1
continue
return cnt == len(abbrev)
text= "Some example text (SET) that demonstrates what I'm looking for. Energy system models (ESM) are used to find specific optima (SCO). Some say computer systems (CUST) are cool. In the summer playing outside (OUTS) should be preferred. Stupid example(s) Stupid example(S) Not stupid example (NSEMPLE), bad example (Bexle)"
abbrev_rx = r'\b(([A-Z])\w*(?:\s+\w+)*?)\s*\((\2[A-Z]*)\)'
print( [x.group() for x in re.finditer(abbrev_rx, text, re.I) if contains_abbrev(x.group(3), x.group(1))] )
See the Python演示 https://ideone.com/oKjTRB.
使用的正则表达式是
(?i)\b(([A-Z])\w*(?:\s+\w+)*?)\s*\((\2[A-Z]*)\)
See the 正则表达式演示 https://regex101.com/r/yMs7TF/1。细节:
-
\b
- 字边界
-
(([A-Z])\w*(?:\s+\w+)*?)
- 第 1 组(text
):捕获到第 2 组的 ASCII 字母,然后是 0+ 个单词字符,后跟任何 0 次或多次出现的 1+ 个空格,后跟 1+ 个单词字符,尽可能少
-
\s*
- 0+ 空格
-
\(
- a (
char
-
(\2[A-Z]*)
- 第 3 组(abbrev
):与第 2 组中的值相同,然后是 0 个或多个 ASCII 字母
-
\)
- a )
char.
一旦有比赛,第 3 组将被传递为abbrev
第 1 组已通过text
to the contains_abbrev(abbrev, text)
方法,这确保了abbrev
是一个大写字符串并且其中的字符abbrev
按照与中相同的顺序进行text
,并且都存在于text
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)