C# 使用正則表達式實作(實現) 複合變數(CompoundVariables)拆解/分析 範例

C# 使用正則表達式實作(實現) 複合變數(CompoundVariables)拆解/分析 範例

C# 使用正則表達式實作(實現) 複合變數(CompoundVariables)拆解/分析 範例


資料來源: chatgpt


C#線上編譯器: https://dotnetfiddle.net/


問題備份

我有一字串如下
"{Name}};; {Value01}|{Value02}"

我想要使用C# 正則表達方式 將其轉換成 字串陣列內如下
"Name}"
";; "
"Value01"
"Value02"
"|"



code

using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        string input = "{Name}};; {Value01}|{Value02}";

        string pattern = @"\{([^}]+)}(\}*)|[^{}]+";

        var matches = Regex.Matches(input, pattern);
        var result = new List<string>();

        foreach (Match match in matches)
        {
            if (match.Groups[1].Success) // 匹配了 {xxx}
            {
                string value = match.Groups[1].Value + match.Groups[2].Value; // 加上多出來的 }
                result.Add(value);
            }
            else
            {
                result.Add(match.Value);
            }
        }

        // 顯示結果
        foreach (var part in result)
        {
            Console.WriteLine($"\"{part}\"");
        }
    }
}



正則表達說明:

\{([^}]+)}(\}*):

([^}]+) 捕捉 {} 中的內容

(\}*) 捕捉在 } 之後緊接著的所有多餘 }(例如 }} 會捕捉第二個)


========================================

|[^{}]+:

捕捉不是 {} 的其他文字,例如 ;; 和 |

2 thoughts on “C# 使用正則表達式實作(實現) 複合變數(CompoundVariables)拆解/分析 範例

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *