如何利用正则递归替换实现多条件模板字符串转换?
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:
- Match the entire
{{...}}block and extract its inner content. - 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

