Python 用于匹配以[开头和结尾]的行的正则表达式

Python 用于匹配以[开头和结尾]的行的正则表达式,python,regex,regex-lookarounds,regex-group,regex-greedy,Python,Regex,Regex Lookarounds,Regex Group,Regex Greedy,我试图在文件中找到以[和]开头的行。我正在使用正则表达式,但无法得到结果 我尝试过使用各种选项的正则表达式,例如\s、\s、\w和\w 重新导入 infle=open(“C:\\Users\\Downloads\\Files\\processed.csv”,“r”) myregex=re.compile(r'(^\[)(\]$)) 列表=[] 对于myregex.findall(infle.read())中的组: 项=“”。加入(组) cleanitem=item.replace('\n',''

我试图在文件中找到以[和]开头的行。我正在使用正则表达式,但无法得到结果

我尝试过使用各种选项的正则表达式,例如\s、\s、\w和\w

重新导入
infle=open(“C:\\Users\\Downloads\\Files\\processed.csv”,“r”)
myregex=re.compile(r'(^\[)(\]$))
列表=[]
对于myregex.findall(infle.read())中的组:
项=“”。加入(组)
cleanitem=item.replace('\n','')
list.append(cleanitem)
打印(列表)
infle.close()
它应该打印所有以[和]开头的行


我如何解决这个问题

在这里,我们可以找到一个带有捕获组的简单表达式,如果我们愿意,类似于:

^(\[.+\])$
测验 正则表达式 如果不需要此表达式,可以在中对其进行修改/更改

正则表达式电路 可视化正则表达式:

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"^(\[.+\])$"

test_str = ("[ and ends with ]\n"
    " [ and ends with ]")

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.