Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用正则表达式搜索字符串列表以查找子字符串_Python_Regex_String - Fatal编程技术网

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

Python 使用正则表达式搜索字符串列表以查找子字符串,python,regex,string,Python,Regex,String,我已经讨论了这里的许多正则表达式问题,并使用了其中的建议,但似乎无法让我的代码静止运行。我有一个字符串列表,我正在尝试查找此列表中包含以下模式之一的条目: 一片空白 空白中的空白 空白中的空白 空白中的空白 那一片空白 那一片空白 空白的空白 空白的空白 例如,我应该能够找到包含诸如“医生的白痴”或“学生的辛勤工作者”等短语的句子 一旦找到,我想列出一个符合这个标准的句子列表。到目前为止,这是我的代码: for sentence in sentences: matched = re.

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

  • 一片空白
  • 空白中的空白
  • 空白中的空白
  • 空白中的空白
  • 那一片空白
  • 那一片空白
  • 空白的空白
  • 空白的空白
例如,我应该能够找到包含诸如“医生的白痴”或“学生的辛勤工作者”等短语的句子

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

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
实际匹配点或星字符,引用文档:

[]

用于指示一组字符。一组:

可以单独列出字符,例如,[amk]将匹配“a”、“m”或“k”

因此,这里有一种方法:

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

此表达式将尝试匹配,that,a或an,然后任何字符都有a或an

在这里,有一个演示它的过程

下面是实际演示:

>>> 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

目前,这段代码将把模式参数连接成一个长字符串,它们之间没有运算符。实际上,您正在搜索正则表达式“a[.]of a[.]of a[.]of a[.]of a…”

您缺少“或”运算符:|。完成此任务的更简单的正则表达式如下:

(a|an|that|the) \b.*\b of (a|an) \b.*\b

你为什么要写这样的东西:
[.*]
,之前花点时间阅读regex教程,不要随意尝试。我以为[.*]会让我搜索任何长度的子字符串和任何字符-我是否误解了这一点?括号用于匹配单个字符,使用
(.*)