Python正则匹配行首单词:提取首个状态为[up]的接口
Got it, let's tackle your two Python regex tasks with clear examples and explanations:
1. Extract the First Word of a Line Using Regex in Python
To grab the first word (a sequence of non-whitespace characters) at the start of a line, we can use a regex that targets the beginning of the line and captures the first continuous non-blank segment.
Here's how to implement it:
import re # For a single line single_line = "Ethernet1/48 up up" first_word_match = re.search(r"^(\S+)", single_line) if first_word_match: print(first_word_match.group(1)) # Output: Ethernet1/48 # For multi-line text multi_line_text = """ GigabitEthernet0/1 down down Ethernet1/48 up up Ethernet1/1 up down """ # Iterate through each line and extract the first word for line in multi_line_text.strip().split("\n"): match = re.search(r"^(\S+)", line) if match: print(match.group(1))
How it works:
^anchors the match to the start of the line(\S+)captures one or more non-whitespace characters (this is our first word)re.search()finds the first occurrence of the pattern in the string
2. Extract the First Interface with Status [up]
Assuming your input is a multi-line string where each line starts with an interface name followed by status values, we can adjust the regex to target lines where the status is up (or [up] if that's your actual format) and capture the first matching interface.
Example Implementation:
import re # Sample input content input_data = """ GigabitEthernet0/1 down down Ethernet1/48 up up Ethernet1/1 up down """ # Match the first interface where the first status is "up" # If your status uses brackets (like [up]), replace "up" with "\[up\]" in the regex interface_match = re.search(r"^(\S+)\s+up", input_data, re.MULTILINE) if interface_match: target_interface = interface_match.group(1) print(target_interface) # Output: Ethernet1/48
Notes:
re.MULTILINEmakes^match the start of every line in the multi-line string, not just the start of the entire string- If the
upstatus is in a different column (e.g., the second status column), adjust the regex to skip the first status field:r"^(\S+)\s+\S+\s+up" - For bracketed statuses like
[up], escape the brackets:r"^(\S+)\s+\[up\]"
内容的提问来源于stack exchange,提问作者ferjani nasraoui
相关产品推荐
相关产品推荐

