如何在Python中编写正则表达式提取指定字符串中的小时数23?
Extracting Hour from Timestamp with Regex in Python
If you need to pull the hour value (23) from the timestamp Sat Apr 18 23:22:15 PDT 2009, here's a reliable regex solution and step-by-step Python implementation:
Regex Pattern
To specifically target the hour (and avoid accidentally matching other digits like the day 18 or year 2009), use this precise pattern:
^\S+ \S+ \S+ (\d{2}):
Breakdown of the pattern:
^: Anchors the match to the start of the string (prevents false matches on later digits in the timestamp)\S+: Matches each of the first three non-whitespace segments ("Sat", "Apr", "18"): Matches the spaces separating those initial segments(\d{2}): Captures exactly two digits—this is our desired hour value:: Ensures we're targeting the start of theHH:MM:SStime component
If you're confident the time segment will always follow HH:MM:SS format, a simpler pattern works just as well:
(\d{2}):\d{2}:\d{2}
This grabs the first two digits before the first colon in any time-like sequence, which is perfect for this timestamp.
Python Implementation
Here's how to use these patterns in Python with the built-in re module:
import re # Your target timestamp timestamp = "Sat Apr 18 23:22:15 PDT 2009" # Using the precise pattern match = re.search(r'^\S+ \S+ \S+ (\d{2}):', timestamp) if match: extracted_hour = match.group(1) print(f"Extracted hour: {extracted_hour}") # Output: Extracted hour: 23 # Using the simpler alternative pattern match_alt = re.search(r'(\d{2}):\d{2}:\d{2}', timestamp) if match_alt: extracted_hour_alt = match_alt.group(1) print(f"Extracted hour (alternative): {extracted_hour_alt}") # Output: Extracted hour (alternative): 23
Key Notes:
- Use raw strings (
r'') for regex patterns in Python to avoid escaping issues with special characters. - Always check if
matchexists (is notNone) before accessinggroup(1)—this preventsAttributeErrorif the timestamp format doesn't match your pattern. re.search()finds the first occurrence of the pattern, which is exactly what we need for this use case.
内容的提问来源于stack exchange,提问作者CFD
相关产品推荐
相关产品推荐

