You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何匹配多字符串并提取主机名与版本信息输出为表格?

Solution for Extracting Hostname and Version into a Table

Hey there! Let's get your Python code working properly to extract those Hostname and Version values and display them in a clean table.

  • re: Python's built-in regular expression library is perfect here—it's lightweight and designed exactly for pattern matching in text.
  • prettytable: A great library for creating readable ASCII tables, which matches your desired output format.

Fixed Code Implementation

Here's a complete, working example that addresses your loop logic and matching issues:

import re
from prettytable import PrettyTable

# Your input text
input_text = "Hostname router1 version 15 xxxx------ Hostname router2 version 14 xxxx------"

# Define the regex pattern to match Hostname and Version pairs
# The pattern captures:
# - Hostname value (\w+): matches word characters (letters/numbers/underscores)
# - Version value (\d+): matches digits
pattern = r"Hostname (\w+) version (\d+)"

# Find all matching pairs in the text
matches = re.findall(pattern, input_text)

# Create and populate the table
table = PrettyTable()
table.field_names = ["Hostname", "Version"]

# Add each match to the table
for hostname, version in matches:
    table.add_row([hostname, version])

# Print the table
print(table)

Output

Running this code will produce exactly the format you want:

+----------+---------+
| Hostname | Version |
+----------+---------+
| router1  |    15   |
| router2  |    14   |
+----------+---------+

Key Explanations

  1. Regex Pattern: r"Hostname (\w+) version (\d+)" is crafted to target exactly the pairs you need. The parentheses () capture the values we want (hostname and version) while ignoring the fixed "Hostname" and "version" labels.
    • \w+: Matches one or more word characters (covers router names like router1, router2, etc.)
    • \d+: Matches one or more digits (covers version numbers like 15, 14)
  2. re.findall(): This method returns all non-overlapping matches of the pattern as a list of tuples—each tuple contains a hostname and version pair, which makes looping through them straightforward.
  3. PrettyTable Setup: We define the column names first, then loop through the matches to add each row. No complicated loop logic needed here!

Troubleshooting Your Original Code

It looks like your original code had an import syntax issue (import re from prettytable... is invalid)—always make sure each import is on its own line, like import re and from prettytable import PrettyTable. Also, using re.findall() simplifies the loop compared to manual iteration over matches.

内容的提问来源于stack exchange,提问作者venkat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:20:04