首页 > 解决方案 > 使用正则表达式获取指定字符串之间的所有文本

问题描述

如何使用正则表达式在 Python3 中的 2 个指定字符串之间获取字符串?

b'SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.11\r\n'

所需的输出:

>>> SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.11
# ipsort.py
import re

f = open("ssh.txt", "r")

line = f.readline()

for line in f:
    version = re.search(r"b'(.*?)\r\n'", line)
    new_file = open("ssh_versions.txt", "a")
    new_file.write(version)
    new_file.close()

Traceback (most recent call last):
  File "ipsort.py", line 11, in <module>
    new_file.write(version)
TypeError: write() argument must be str, not None

标签: pythonregexpython-3.x

解决方案


您需要\在正则表达式中加倍,因为否则它会匹配 CR 和 LF 字符而不是文字\rand \n

您还需要使用version.group(1)来获取捕获组匹配的字符串。

version = re.search(r"b'(.*?)\\r\\n'", line)
if version:
    with open("ssh_versions.txt", "a") as new_file:
        new_file.write(version.group(1))

推荐阅读