【问题标题】:Python-Retrieve specific text from a string textPython-从字符串文本中检索特定文本
【发布时间】:2021-03-12 03:27:31
【问题描述】:

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

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

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

【问题讨论】:

标签: python regex


【解决方案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

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2021-09-04
    • 2022-11-24
    • 1970-01-01
    • 2020-04-26
    • 2022-10-13
    • 1970-01-01
    • 2019-10-17
    • 2013-08-08
    • 2012-03-30
    相关资源
    最近更新 更多