Python正则表达式来查找两个字符串之间的字符串

2024-04-23 22:11:35 发布

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

我试图使用正则表达式来查看字符串的特定部分并获取介于两者之间的内容,但我无法为此获得正确的正则表达式模式。在

我最大的问题是试图为此建立一个Regex模式。我试着列举了一系列的变化。应该很近。在

import re

toFind = ['[]', '[x]']
text = "| Completed?|\n|------|:---------:|\n|Link Created    |   []   |\n|Research Done   |   [X] "

# Regex to search between parameters and make result lowercase if there are any uppercase Chars
result = (re.search("(?<=Link Created)(.+?)(?=Research Done)", text).lower())

# Gets rid of whitespace in case they move the []/[x] around
result = result.replace(" ", "")

if any(x in result for x in toFind):
    print("Exists")
else:
    print("Doesn't Exist")

快乐之路: 我使用string(文本)并使用Regex表达式获取链接创建和研究完成之间的子字符串。在

然后将结果设为小写并去掉空白,以防它们移动[]/[x]s。然后它查看“[]”或“[x]”的字符串(result)并打印。在

实际产量: 目前我一直得到的是没有,因为正则表达式语法是关闭的。。。在


Tags: 字符串textinresearchif模式link
3条回答

如果希望.匹配换行符,可以使用re.S选项。在

另外,在继续调用之前检查正则表达式是否匹配似乎是一个更好的主意。您对lower()的调用给了我一个错误,因为正则表达式不匹配,所以只有在result的计算结果为true时调用result.group(0).lower()更安全。在

import re

toFind = ['[]', '[x]']
text = "| Completed?|\n|   |:    -:|\n|Link Created    |   []   |\n|Research Done   |   [X] "

# Regex to search between parameters and make result lowercase if there are any uppercase Chars
result = (re.search("(?<=Link Created)(.+?)(?=Research Done)", text, re.S))

if result:
    # Gets rid of whitespace in case they move the []/[x] around
    result = result.group(0).lower().replace(" ", "")

    if any(x in result for x in toFind):
        print("Exists")
    else:
        print("Doesn't Exist")
else:
    print("re did not match")

PS:所有的re选项都记录在re module documentation中。搜索re.DOTALL以获得关于re.S(它们是同义词)的详细信息。如果要组合选项,请使用按位或。E、 g.,re.S|re.I将使.匹配换行符并进行不区分大小写的匹配。在

我相信是\n换行符造成了问题。您可以使用[\s\S]+来解决这个问题:

import re

toFind = ['[]', '[x]']
text = "| Completed?|\n|   |:    -:|\n|Link Created    |   []   |\n|Research Done   |   [X] "

# New regex to match text between
# Remove all newlines, tabs, whitespace and column separators
result = re.search(r"Link Created([\s\S]+)Research Done", text).group(1)
result = re.sub(r"[\n\t\s\|]*", "", result)

if any(x in result for x in toFind):
    print("Exists")
else:
    print("Doesn't Exist")

似乎regex对于这个特定的工作来说是过度的,除非我遗漏了一些东西(我也不清楚为什么需要从子字符串中删除空白的步骤)。您可以在“Link Created”上拆分,然后将下面的字符串拆分为“Research Done”。在

text = "| Completed?|\n|   |:    -:|\n|Link Created    |   []   |\n|Research Done   |   [X] "

s = text.split("Link Created")[1].split("Research Done")[0].lower()

if "[]" in s or "[x]" in s:
    print("Exists")
else:
    print("Doesn't Exist")

# Exists

相关问题 更多 >