首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用于匹配以[开头并以]结尾的行的RegEx

问用于匹配以[开头并以]结尾的行的RegEx
EN

Stack Overflow用户
提问于 2019-05-31 06:12:43
回答 1查看 1.2K关注 0票数 -1

我正在尝试查找文件中以开头和结尾的行。我正在使用正则表达式,但无法获得结果。

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

代码语言:javascript
复制
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()

它应该打印所有以开头和结尾的行。

我该如何解决这个问题?

EN

回答 1

Stack Overflow用户

发布于 2019-05-31 06:16:28

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

代码语言:javascript
复制
^(\[.+\])$

测试

代码语言:javascript
复制
# 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.

DEMO

RegEx

如果这个表达式不需要,可以在regex101.com中修改/更改。

RegEx电路

jex.im可视化正则表达式:

​

​

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56386287

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档