Python-从字符串文本中检索特定文本

时间:2021-02-26 13:08:39

标签: python regex

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

原始字符串: (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

尝试使用替换和拆分方法,但没有给出我正在寻找的准确输出。任何指针将不胜感激。

1 个答案:

答案 0 :(得分:1)

\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

我希望这会有所帮助。

相关问题