簡體   English   中英

如何使用正則表達式僅在逗號上分割而不在尖括號中?

[英]How do I use regex to split only on commas not in angle brackets?

我有字符串DobuleGeneric<DoubleGeneric<int,string>,string>

我正在嘗試獲取2個類型參數: DoubleGeneric<int,string>string

最初,我在','上使用了拆分。 這是可行的,但是僅當泛型參數不是主題本身泛型時。

我的代碼:

string fullName = "DobuleGeneric<DoubleGeneric<int,string>,string>";
Regex regex = new Regex( @"([a-zA-Z\._]+)\<(.+)\>$" );
Match m = regex.Match( fullName );
string frontName = m.Groups[1].Value;
string[] innerTypes = m.Groups[2].Value.Split( ',' );

foreach( string strInnerType in innerTypes ) {
        Console.WriteLine( strInnerType );
}

問題:如何對未封裝在尖括號中的逗號進行正則表達式拆分?

兩個逗號都在尖括號之間! 正則表達式在解析復雜的嵌套語法時做得不好。 問題應該是,如何找到一個逗號,該逗號位於尖括號之間,而不是尖括號之間。 我認為使用正則表達式無法做到這一點。

如果可能,請嘗試使用反射。 您也可以使用CS-Script編譯代碼段,然后使用Reflection來檢索所需的信息。

要拆分給出的示例,可以使用以下示例。 但是,這不是通用的。 可以根據您期望的其他字符串將其設為通用。 根據您使用的字符串的不同,此方法可能會變得很復雜。 但是我建議在這里使用羅斯林是過分的...

string fullName = "DobuleGeneric<DoubleGeneric<int,string>,string>"; 
Regex Reg = 
    new Regex(@"(?i)<\s*\p{L}+\s*<\s*\p{L}+\s*,\s*\p{L}+\s*>\s*,\s*\p{L}+\s*>");
Match m = Reg.Match(fullName);
string str = m.ToString().Trim(new char[] { '<', '>' });
Regex rr = new Regex(@"(?i),(?!.*>\s*)");
string[] strArr = rr.Split(str);

我希望這有幫助。

答案是正確的,使用Regex是錯誤的方法。

最后我做一個線性調整,更換封裝在括號中的項~ s,然后做了分裂。

static void Main( string[] args ) {

    string fullName = "Outer<blah<int,string>,int,blah<int,int>>";          

    Regex regex = new Regex( @"([a-zA-Z\._]+)\<(.+)\>$" );
    Match m = regex.Match( fullName );
    string frontName = m.Groups[1].Value;
    string inner = m.Groups[2].Value;

    var genArgs = ParseInnerGenericArgs( inner );

    foreach( string s in genArgs ) {
        Console.WriteLine(s);
    }
    Console.ReadKey();
}

private static IEnumerable<string> ParseInnerGenericArgs( string inner ) {
    List<string> pieces = new List<string>();
    int angleCount = 0;
    StringBuilder sb = new StringBuilder();
    for( int i = 0; i < inner.Length; i++ ) {
        string currChar = inner[i].ToString();
        if( currChar == ">" ) {
            angleCount--;
        }
        if( currChar == "<" ) {
            angleCount++;
        }
        if( currChar == ","  &&  angleCount > 0 ) {

            sb.Append( "~" );

        } else {
            sb.Append( currChar );
        }

    }
    foreach( string item in sb.ToString().Split( ',' ) ) {
        pieces.Add(item.Replace('~',','));
    }
    return pieces;
}

這是我將使用的正則表達式:

\<(([\w\.]+)(\<.+\>)?)\,(([\w\.]+)(\<.+\>)?)$

([\\w\\.]+)匹配“ DoubleGeneric”。 (\\<.+\\>)? 匹配可能的通用參數,例如DoubleGeneric <OtherGeneric<int, ...>>

關鍵是,無論您有多少個嵌套的泛型參數,整個表達式中都只有一個“>”。

您可以使用m.Gruops [1]和m.Groups [4]獲取第一個和第二個Type。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM