如何使用Python提取字符串中多组起始词与结束词间的内容
Extracting Distance Values Between Specific Delimiters
To solve this problem, we can use regular expressions to match and extract the values between your specified start and end delimiters. The key is to account for all variations of the start delimiters (like Dist:, Distance:, Dist**., Dist**:, Dist.) and end delimiters (feet, ft, Direction) in a single pattern.
Regex Pattern
Here's a pattern that covers all the delimiter variants from your input string:
(?<=\s(?:Dist(?:\*\*)?[:.]|Distance:)\s)(.*?)(?=\s(?:feet|ft|Direction))
Breakdown of the Pattern:
- Positive Lookbehind (
(?<= ... )): Ensures we're matching after one of the valid start delimiters:\s: Space before the start delimiter(?:Dist(?:\*\*)?[:.]|Distance:): Matches any of the start variants:Dist(?:\*\*)?[:.]:Distoptionally followed by**, then either:or.|Distance:: OrDistance:
\s: Space after the start delimiter
- Capturing Group (
(.*?)): Non-greedily captures the distance value (stops at the first end delimiter) - Positive Lookahead (
(?= ... )): Ensures we're matching before one of the valid end delimiters:\s: Space before the end delimiter(?:feet|ft|Direction): Matchesfeet,ft, orDirection
Example Implementation (Python)
Here's how you can use this pattern in Python to extract all values from your input string:
import re input_str = "Top of Prod. Zone Dist: 170 feet Direction: FNL Dist: 596 feet Direction: Top of Prod. Zone Distance: 528 ft Direction: FNL Distance: 114 ft Direction: Top of Prod. Zone Dist**. 170 ft Direction: FNL Dist**: 596 ft Direction: Top of Prod. Zone Dist. Direction: FNL Dist: 596 Direction: Top of Prod. Zone Dist. 78 Direction: FNL Dist: 596 Direction: " pattern = r'(?<=\s(?:Dist(?:\*\*)?[:.]|Distance:)\s)(.*?)(?=\s(?:feet|ft|Direction))' matches = re.findall(pattern, input_str) print("Extracted distance values:") for idx, value in enumerate(matches, 1): print(f"{idx}. {value}")
Extracted Values from Your Input
Running the above code on your input string will yield the following values:
- 170
- 596
- 528
- 114
- 170
- 596
- 596
- 78
- 596
内容的提问来源于stack exchange,提问作者Shadkhan
相关产品推荐
相关产品推荐

