假设,我有一个字符串str=“我在西南大学学习。我21岁。我在西北大学学习。我22岁。”
使用正则表达式,我需要打印以"I“开头并以"University”结尾的每个子字符串。
产出应如下:
“我在西南大学学习”
我在西北大学学习
发布于 2022-10-09 22:37:33
也许你可以这样做:
import re
txt = "I study at Southwestern University. I am 21. I study at Northwestern University. I am 22."
# First you get the substrings with split
txt_substrings = txt.split(".")
for i in txt_substrings:
# We need strip to delete blank spaces at the beginning of the sentence
i = i.strip()
dumb = re.search("^I.*University$", i)
if dumb:
print(f"Find substring: {i}")当使用regex时:
更多信息在re 图书馆中。
希望能帮上忙!
https://stackoverflow.com/questions/74008815
复制相似问题