gpt4 book ai didi

Python Regex 在两个字符串之间查找字符串

转载 作者:太空宇宙 更新时间:2023-11-03 23:57:36 31 4
gpt4 key购买 nike

我正在尝试使用 Regex 来查看字符串的特定部分并获取介于两者之间的内容,但我无法为此获得正确的 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")

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

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

实际输出:目前我一直得到的是 None 因为 Regex 语法已关闭......

最佳答案

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

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

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 的详细信息(它们是同义词)。如果要组合选项,请使用按位或。例如,re.S|re.I 将让 . 匹配换行符并进行不区分大小写的匹配。

关于Python Regex 在两个字符串之间查找字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56976836/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com