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

如何利用正则递归替换实现多条件模板字符串转换?

Can This Regex Replacement for Conditional Templates Be Implemented?

Absolutely! Your goal of converting template patterns like {{test_data}}, {{!test_data}}, and {{test_data1&&!test_data2}} into their prefixed counterparts is totally achievable—your current regex just isn't accounting for repeated conditional terms connected by &&. Let's break down how to fix this.

The Core Problem with Your Existing Regex

Your current pattern only handles single variables plus an optional connector, which is why it fails for multi-condition cases like {{test_data1&&!test_data2}}. It can't recursively or globally match all variable terms inside the {{}} block.

Solution 1: Double Replacement (Clear & Maintainable)

The simplest approach is to split the task into two steps:

  1. Match the entire {{...}} block and extract its inner content.
  2. Process that inner content to prefix every variable with mystring., while preserving && connectors.

Example Implementation (C#/.NET)

Since your regex101 link uses the .NET flavor, here's a code snippet using a MatchEvaluator to handle the nested replacement:

string input = "{{test_data}} {{!test_data}} {{test_data1&&!test_data2}}";
string result = Regex.Replace(input, @"{{(.*?)}}", match => 
    // First, add spaces around && for readability (optional but matches your desired output)
    Regex.Replace(match.Groups[1].Value.Replace("&&", " && "), @"(!?)(\w+)", "$1mystring.$2")
);

How It Works:

  • The outer regex {{(.*?)}} captures everything inside each template block.
  • The inner regex (!?)(\w+) targets each variable term (with or without a leading !), replacing it with $1mystring.$2 (preserving the ! if present).
  • The .Replace("&&", " && ") adds spaces around connectors to match your desired output format.

Solution 2: Single Regex with Nested Replacement (For .NET)

If you prefer a one-line regex replacement (supported by .NET's advanced substitution syntax), you can use:

  • Pattern: {{(.*?)}}
  • Replacement: ${1/(!?)(\w+)/$1mystring.$2/g}

This works by first capturing the inner content of the {{}} block, then running a global replacement on that captured content to prefix each variable.

Test Results

All your test cases will be converted correctly:

  • {{test_data}} → mystring.test_data
  • {{!test_data}} → !mystring.test_data
  • {{test_data1&&!test_data2}} → mystring.test_data1 && !mystring.test_data2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:13:52