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

C#通用方法实现:从字符串中提取两个不同子串求助

通用子串提取解决方案

Got it, let's work through this problem together! You need a reliable way to pull those two values (HIGH/LOW or their variations) from a variable-length string, and the structure around them stays consistent—perfect, regex is going to be your best bet here for universal compatibility.

思路 Breakdown

First, let's confirm the fixed structure we're targeting (even if the rest of the string varies):

/*Description:
*RANGE:
*HIGH
*LOW
*/

The key anchors here are:

  • *RANGE: is our trigger line that precedes the two values we need
  • Each value sits on its own line, prefixed with a * (we'll account for possible spaces too)
  • The block wraps up with */

Pseudocode Implementation

Here's a straightforward, language-agnostic approach you can adapt to any programming language:

// Step 1: Define a regex pattern that locks onto the RANGE block
regex_pattern = /\*RANGE:\s*\n\*(.*?)\s*\n\*(.*?)\s*\n/

// Step 2: Run the pattern against your target string
match_results = regex_match(target_string, regex_pattern)

// Step 3: Extract the two values
substring1 = match_results[1]  // This will be the HIGH equivalent
substring2 = match_results[2]  // This will be the LOW equivalent

Concrete Example (Python)

If you're working in Python, here's how you'd put this into action:

import re

# Your example string (works with any length as long as the RANGE structure holds)
target_str = """/*Description:
*RANGE:
*HIGH
*LOW
*/"""

# Regex pattern that handles optional spaces and standard newlines
pattern = r'\*RANGE:\s*\n\*\s*(.*?)\s*\n\*\s*(.*?)\s*\n'
match = re.search(pattern, target_str)

if match:
    substring1 = match.group(1)
    substring2 = match.group(2)
    print(f"substring1: {substring1}")  # Outputs "HIGH"
    print(f"substring2: {substring2}")  # Outputs "LOW"

Why This Works Universally

  • It doesn't care how long the rest of the string is—whether the Description section is 1 line or 100, the regex only focuses on the *RANGE: block
  • The \s* flags handle any extra spaces (like if lines are formatted as * HIGH instead of *HIGH)
  • The non-greedy .*? ensures we only capture content from each individual line, no cross-line spills

Quick Adjustment for Windows Line Breaks

If your string uses Windows-style \r\n line breaks instead of Unix \n, just tweak the regex to account for that:

pattern = r'\*RANGE:\s*\r?\n\*\s*(.*?)\s*\r?\n\*\s*(.*?)\s*\r?\n'

This will work seamlessly with both newline formats.

内容的提问来源于stack exchange,提问作者Felix J.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:21:16