简体   繁体   English

如何使用Python从单行开始[以#结尾]的所有字符串?

[英]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.

相关问题 我怎样才能得到一条线? - How can I get a single line out? 如何从 MongoDb 获取包含开始日期和结束日期的数据? - How can I get data from MongoDb with starting and ending date? 如何在python的正则表达式模块中获取多个以字符串开头和以字符串结尾的字符串? - How to get multiple strings of starting with a string and ending with string in regular expression module of python? 如何列出以特定字符开头和结尾的所有Unicode字符串? - How to list all Unicode strings starting and ending with a particular character? 如何在 python 异常中取出错误行文本? - How can i get out the error line text in python exceptions? Given a C++ file with many function definitions, how to get the starting and ending index of a particular function using Python? - Given a C++ file with many function definitions, how to get the starting and ending index of a particular function using Python? 当使用 Python 和 Selenium 抓取 web 时,如何从单个页面获取所有 href 链接? - How can I get all the href links from a single page when web scraping using Python and Selenium? 如何使用python去除开始和结束标签 - how to remove the starting and ending tags using python Beautiful soup Stream 提取。 如何从列表列表中提取包含公共元素(行开始和结束坐标)的新列表列表? - Stream Extraction. How can I extract from a list of lists a new list of lists containing common elements (line starting and ending coordinates)? 如何让 Python 在第一行开始读取文件? - How do I get Python to starting reading a file on the first line?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM