python-3.x - 两个正则表达式的串联

标签 python-3.x regex

我有以下导出的文本文件:

14:00:01 type1 "xyz" has no relationships... ಠ_ಠ
14:00:01 type2 "xyza" has no relationships... ಠ_ಠ
14:00:01 type2 "aaaa" has no relationships... ಠ_ಠ
14:00:01 type3 "asdg" has no relationships... ಠ_ಠ
14:00:01 type4 "dhj" has no relationships... ಠ_ಠ

我正在尝试找到一种方法来从此文件中检索两个信息

  1. 类型(在本例中为时间之后、双引号内之前的元素)
  2. 双引号内的内容

预期输出:

type1 xyz

type2 xyza

type2 aaaa

type3 asdg

type4 dhj

使用我当前的代码,我可以获取双引号内的内容,但我不知道如何获取类型并将其与我的正则表达式合并:

import os, yaml
import argparse
import re
with open('stackoverflow.txt') as f:
    content = f.readlines()
    matches=re.findall(r'\"(.+?)\"',str(content))#get the content within the double quote
for x in matches:
    print(x)

当前输出:

xyz

xyza

aaaa

asdg

dhj

最佳答案

如果您的 txt 文件始终具有该结构,我会简单地这样做:

with open('stackoverflow.txt') as f:
    matches = [' '.join(line.split(' ')[1:3]) for line in f.readlines()]

for x in matches:
    print(x)

输出:

type1 "xyz"
type2 "xyza"
type2 "aaaa"
type3 "asdg"
type4 "dhj"

关于python-3.x - 两个正则表达式的串联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67003852/

相关文章:

python - 为 Mac django-admin 启动 Python 3 的 Django 不工作

python-3.x - 使用 playwright-python 下载 pdf 文件

regex - Spring security 3 带索引的拦截url模式

java - 正则表达式:匹配多行输入的模式

c# - 替换为正则表达式

objective-c - 在 xcode 中用 "{"替换 "(newline){"的正则表达式

python - Pandas 多个箱线图 - 如何减少图之间的间距?

python - 如何使用 ConfigObj 附加到现有配置文件?

python - 使用 beautifulsoup 进行网页抓取

javascript - 在js中分割一个模式不匹配的字符串?