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

如何使用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(?:\*\*)?[:.]: Dist optionally followed by **, then either : or .
      • |Distance:: Or Distance:
    • \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): Matches feet, ft, or Direction

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:23:39