【问题标题】:RegEx for matching lines starting with [ and ending with ] [duplicate]用于匹配以 [ 开头并以 ] 结尾的行的正则表达式 [重复]
【发布时间】:2019-05-30 22:12:42
【问题描述】:

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

我尝试过使用各种选项的正则表达式,例如 \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()

它应该打印所有以 [ 开头并以 ] 结尾的行。

我该如何解决这个问题?

【问题讨论】:

    标签: python regex regex-lookarounds regex-group regex-greedy


    【解决方案1】:

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

    ^(\[.+\])$
    

    测试

    # 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

    正则表达式

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

    正则表达式电路

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-22
      • 2014-07-17
      • 2011-09-10
      • 2015-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-20
      相关资源
      最近更新 更多