[英]How can I get all strings starting with [ and ending with ] out of a single line using Python?
Sorry I am very new to python and trying to figure out how to take out a specific string sequence out of all the string 对不起,我是python的新手,并试图弄清楚如何从所有字符串中取出特定的字符串序列
I tried using re but I don't quite get it.. 我尝试使用re但我不太明白..
import re
userinput = input('Enter the name of the file:')
file = open(userinput)
info = file.readlines()
info = re.sub(r'\[[.+]\]','',info)
print(info)
file.close()
if file includes: notokay[okay]notokayas[okay2]sjnfksdnfnslk 如果文件包括:notokay [okay] notokayas [okay2] sjnfksdnfnslk
I want to be able to extract: okay, okay2 我希望能够提取:好的,好的2
Use re.findall
使用
re.findall
Ex: 例如:
import re
s = "notokay[okay]notokayas[okay2]sjnfksdnfnslk"
print(re.findall(r"\[(.*?)\]", s))
Output: 输出:
['okay', 'okay2']
您可以使用以下模式匹配:
\[(.*?)\]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.