python - 使用正则表达式获取指定字符串之间的所有文本
问题描述
如何使用正则表达式在 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
解决方案
您需要\
在正则表达式中加倍,因为否则它会匹配 CR 和 LF 字符而不是文字\r
and \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))
推荐阅读
- javascript - Barba Js 在第一次链接上重新加载页面
- html - 如何使用引导程序将 div 向右对齐?
- r - R 中的代码可读性:如何避免 get() 和 assign()
- c# - ReSharper NUnit3 - 使用没有复制本地副本的 dll
- python - Pytorch NLP 模型在进行推理时不使用 GPU
- javascript - 如何在函数外传输数据
- google-cloud-platform - 在 Google Cloud Run 中容器化应用程序时出现 Docker 错误
- javascript - JS棋盘阅读器Y坐标问题
- python - 与 python 类似的句子 like bash with jq
- r - 在数据集中使用过滤器功能时的问题