gpt4 book ai didi

python - 用正则表达式替换不需要的字符

转载 作者:行者123 更新时间:2023-12-04 09:06:47 24 4
gpt4 key购买 nike

我有一个在一行上的字符串:

https[:]//sometest[.]com,http[:]//differentt,est.net,https://lololo.com
请注意,我特意放置了 ,进入第二个网址。我正在尝试更换 ,哪里 http(s)满足。到目前为止,我试过这个:
pattern_src = r"http(.*)"
for i, line_src in enumerate(open("/Users/test/Documents/tools/dump/email.txt")):
for match in re.finditer(pattern_src, line_src):
mal_url = (match.group())
source_ = mal_url

string = source_
for ch in ["[" , "]"]:
for c in [","]:
string = string.replace(c,"\n")
string = string.replace(ch,"")
with open("/Users/test/Documents/tools/dump/urls.txt", 'w') as file:
file.write(string)
print(string)
但是你可以清楚地看到它会取代所有的 ,在字符串中。所以我的问题是,我将如何只更换 ,之前 http并拥有每个 http网址换行?

最佳答案

>>> s = 'https[:]//sometest[.]com,http[:]//differentt,est.net,https://lololo.com'
>>> print(re.sub(r',(?=http)', '\n', s))
https[:]//sometest[.]com
http[:]//differentt,est.net
https://lololo.com
,(?=http)将匹配 ,仅当后面跟着 http .这里 (?=http)是一个积极的前瞻断言,它允许在不消耗这些字符的情况下检查条件。
Reference - What does this regex mean?有关环视或我的书的详细信息: https://learnbyexample.github.io/py_regular_expressions/lookarounds.html

关于python - 用正则表达式替换不需要的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63423071/

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