【问题标题】:Finding the content between two characters regex? [closed]查找两个字符正则表达式之间的内容? [关闭]
【发布时间】:2020-05-28 10:05:51
【问题描述】:

我有一个.txt 文件,其中包含每一行上特定项目的所有信息,格式如下:

1 +'item 1'+ [0, 0]
2 +'item 2'+ [0, 0]

第一个数字是项目ID,+ 符号之间的字符串是项目名称,最后的列表是项目的统计信息。我需要使用正则表达式来获取+ 符号之间的名称,但是我找到的所有答案都不完全是我想要的,而且我根本不太了解正则表达式。我应该使用什么模式来查找名称?

类似的问题/答案,并不能真正回答我的问题:one, two

【问题讨论】:

  • 如果您可以向我们展示您迄今为止所做的尝试,那么改进您的尝试通常比我们从头开始更容易。此外,当我尝试写下我已经尝试过的内容时,我经常会找到自己的答案。
  • "1 +'item 1'+ [0, 0]".split('+')[1] 而不是正则表达式呢?
  • "(?<=')[^']+?(?=')" 怎么样?

标签: python regex python-3.x


【解决方案1】:

最好使用 split 方法,但如果你真的需要使用正则表达式,你可以这样做:

import re

file = 'filepath/to/your/text/file.txt'

with open(file, encoding='utf-8') as f:
    pattern = r'\'(.+)\''
    solution = re.findall(pattern, f.read())

print(solution)

【讨论】:

    【解决方案2】:

    尝试使用常规字符串方法隔离项目名称,见下文。

    saved_names = []
    with open('file.txt', 'r') as fr:
        for line in fr.readlines():
            name = line.split('+')[1]
            saved_names.append(name)
    

    或者使用正则表达式:

    # compile pattern, catch all items.
    pattern = re.compile(r'(.+)\s\+(.+)\+\s(.+)')
    
    saved = []
    with open('file.txt', 'r') as fr:
        for line in fr.readlines():
            name = match(pattern, line.strip('\n'))
            id, name, data = matches.groups()
            saved.append((id, name, data))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-06
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      相关资源
      最近更新 更多