python从字符串文本中检索特定文本

2024-05-19 21:14:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从原始字符串中检索具有固定开始和结束模式的字符串:

原始字符串:(0, '\x1b[0;36mlocal\x1b[0;0m:\n\x1b[0;32mdbsvr-234-00ty.triu.ty.test.com\x1b[0;0m', [])

所需字符串:dbsvr-234-00ty.triu.ty.test.com

尝试使用替换&;split方法,但它没有给出我想要的准确输出。任何指点都将不胜感激


Tags: 方法字符串testcom模式ampsplitx1b
1条回答
网友
1楼 · 发布于 2024-05-19 21:14:15

\x1b[0;36m部分包含ANSI字符。你需要先把它们清理干净。您可以通过一个库(正如@Thomas Weller所建议的)删除它,或者只需使用正则表达式来清理字符串。以下代码从给定的原始字符串中删除ANSI字符

import re

ANSI_ESCAPE_REGEX = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]')

original_string = """(0, '\x1b[0;36mlocal\x1b[0;0m:\n\x1b[0;32mdbsvr-234-00ty.triu.ty.test.com\x1b[0;0m', [])"""

# Clean color codes(ANSI Chars) from the string
clean_string = ANSI_ESCAPE_REGEX.sub('',original_string)
# (0, 'local:\ndbsvr-234-00ty.triu.ty.test.com', [])

之后,可以再次使用正则表达式查找所需字符串:

# Try to match desiderd string
TARGET_REGEX = re.compile('.*\\n([-\.\w]*).*')
result = TARGET_REGEX.match(clean_string)
desired_str = result.group(1)
# dbsvr-234-00ty.triu.ty.test.com

我希望这会有帮助

相关问题 更多 >