python - 使用正则表达式搜索字符串列表以查找子字符串 Python

标签 python regex string

我已经浏览了这里的许多正则表达式问题并使用了其中的建议,但似乎无法让我的代码继续运行。我有一个字符串列表,我试图在此列表中查找包含以下模式之一的条目:

  • 空白中的空白
  • 空白的空白
  • 空白的空白
  • 空白的空白
  • 空白中的空白
  • 空白中的空白
  • 空白中的空白
  • 空白中的空白

例如,我应该能够找到包含“an idiot of a doctor”或“the Hard-worker of a Student”等短语的句子。

一旦找到,我想列出满足这个标准的句子。到目前为止,这是我的代码:

for sentence in sentences:
    matched = re.search(r"a [.*]of a " \
                        r"an [.*]of an " \
                        r"a [.*]of an" \
                        r"an [.*]of a " \
                        r"that [.*]of a " \
                        r"that [.*]of an " \
                        r"the [.*]of a " \
                        r"the [.*]of an ", sentence)
    if matched:
        bnp.append(matched)

#Below two lines for testing purposes only
print(matched)
print(bnp)

尽管事实上有一些短语应该满足列表中的条件,但此代码没有显示任何结果。

最佳答案

[.*] 是一个字符类,因此您要求 regex 实际匹配点或星号字符,引用 re's文档:

[]

Used to indicate a set of characters. In a set:

Characters can be listed individually, e.g. [amk] will match 'a', 'm', or 'k'.

...

所以,这是一种方法:

(th(at|e)|a[n]?)\b.*\b(a[n]?)\b.*

此表达式将尝试匹配 the、that、a 或 an,然后直到那里的任何字符都是 a 或 an。

在这里link ,有其过程的演示。

这是实际演示:

>>> import re
>>>
>>> regex = r"(th(at|e)|a[n]?)\b.*\b(a[n]?)\b.*"
>>> test_str = ("an idiot of a doctor\n"
    "the hard-worker of a student.\n"
    "an BLANK of an BLANK\n"
    "a BLANK of an BLANK\n"
    "an BLANK of a BLANK\n"
    "that BLANK of a BLANK\n"
    "the BLANK of a BLANK\n"
    "the BLANK of an BLANK\n")
>>>
>>> matches =  re.finditer(regex, test_str, re.MULTILINE | re.IGNORECASE) 
>>> 
>>> for m in matches:
        print(m.group())


an idiot of a doctor
the hard-worker of a student.
an BLANK of an BLANK
a BLANK of an BLANK
an BLANK of a BLANK
that BLANK of a BLANK
the BLANK of a BLANK
the BLANK of an BLANK

关于python - 使用正则表达式搜索字符串列表以查找子字符串 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41706025/

相关文章:

python - 如何使用 sympy.pprint() 在 ipython 中进行精美打印

php - 用于解析YouTube嵌入式代码的正则表达式

javascript - 减少并检查最长的字符串

python - Pygame碰撞代码

python - 尝试使用operator.or_减少Django Q对象似乎会导致减少 'AND'

Python 困惑——约定、名称和值

javascript - 在 $.each() 中搜索并替换

php - 在 MySQL 数据库中执行 REGEXP 查找和替换的最快方法是什么?

Python:使用 "..%(var)s.."% locals() 是一个好习惯吗?

python - 如何将字符串列表更改为整数 - Python