簡體   English   中英

如何使用Python從單行開始[以#結尾]的所有字符串?

[英]How can I get all strings starting with [ and ending with ] out of a single line using Python?

對不起,我是python的新手,並試圖弄清楚如何從所有字符串中取出特定的字符串序列

我嘗試使用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()

如果文件包括:notokay [okay] notokayas [okay2] sjnfksdnfnslk

我希望能夠提取:好的,好的2

使用re.findall

例如:

import re

s = "notokay[okay]notokayas[okay2]sjnfksdnfnslk"
print(re.findall(r"\[(.*?)\]", s))

輸出:

['okay', 'okay2']

您可以使用以下模式匹配:

\[(.*?)\]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM