我正在尝试查找文件中以开头和结尾的行。我正在使用正则表达式,但无法获得结果。
我尝试过使用各种选项的正则表达式,例如\s、\S、\W和\w。
import re
infile=open("C:\\Users\\Downloads\\Files\\processed.csv","r")
myregex = re.compile(r'(^\[)(\]$)')
list=[]
for groups in myregex.findall(infile.read()):
item=''.join(groups)
cleanitem=item.replace('\n','')
list.append(cleanitem)
print (list)
infile.close()它应该打印所有以开头和结尾的行。
我该如何解决这个问题?
发布于 2019-05-31 06:16:28
在这里,我们可以找到一个简单的带有捕获组的表达式,如果我们喜欢,类似于:
^(\[.+\])$测试
# 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.RegEx
如果这个表达式不需要,可以在regex101.com中修改/更改。
RegEx电路
jex.im可视化正则表达式:

https://stackoverflow.com/questions/56386287
复制相似问题