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

C# 如何提取动态指定分隔符包裹的字符串内容

实现思路

核心使用带捕获组的正则表达式实现,支持动态传入分隔符。实现时需要先对分隔符做正则特殊字符转义,避免分隔符本身包含.、*、+等正则元字符时匹配失效。同时使用非贪婪匹配规则,确保每次只匹配两个相邻分隔符中间的内容,不会出现跨占位符匹配的问题。

代码实现

Python 版本

import re

def extract_placeholders(content: str, left_delimiter: str, right_delimiter: str = None) -> list:
    # 未传右分隔符时默认和左分隔符一致
    right_delimiter = right_delimiter or left_delimiter
    # 转义分隔符中的正则特殊字符
    escaped_left = re.escape(left_delimiter)
    escaped_right = re.escape(right_delimiter)
    # 构造正则规则,捕获两个分隔符中间的内容
    pattern = re.compile(f"{escaped_left}(.*?){escaped_right}")
    # 返回所有匹配到的捕获组内容
    return pattern.findall(content)

# 测试用例1:使用%作为左右相同的分隔符
test_str1 = "This is a test string. It was opened on %Date% for the customer named %Customer%."
print(extract_placeholders(test_str1, "%"))
# 输出:['Date', 'Customer']

# 测试用例2:使用{{和}}作为左右不同的分隔符
test_str2 = "Hello {{UserName}}, your order id is {{OrderId}}"
print(extract_placeholders(test_str2, "{{", "}}"))
# 输出:['UserName', 'OrderId']

JavaScript 版本

// 正则特殊字符转义工具函数
function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

function extractPlaceholders(content, leftDelimiter, rightDelimiter) {
  // 未传右分隔符时默认和左分隔符一致
  rightDelimiter = rightDelimiter || leftDelimiter;
  const escapedLeft = escapeRegExp(leftDelimiter);
  const escapedRight = escapeRegExp(rightDelimiter);
  const pattern = new RegExp(`${escapedLeft}(.*?)${escapedRight}`, 'g');
  const result = [];
  let match;
  while ((match = pattern.exec(content)) !== null) {
    result.push(match[1]);
  }
  return result;
}

// 测试用例
const testStr = "This is a test string. It was opened on %Date% for the customer named %Customer%.";
console.log(extractPlaceholders(testStr, "%"));
// 输出:['Date', 'Customer']

内容的提问来源于stack exchange,提问作者atalay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:45:02