簡體   English   中英

復雜正則表達式拆分的需求模式

[英]Need pattern for a complex Regex Split

我想分割以下字符串

// Comments
KeyA : SomeType { SubKey : SubValue } KeyB:'This\'s a string'
KeyC : [ 1 2 3 ] // array value

進入

KeyA
:
SomeType
{ SubKey : SubValue }
KeyB
:
This's a string
KeyC
:
[ 1 2 3 ]

(:和空格是定界符,盡管:保留在結果中;注釋被忽略; {},[]或''之間沒有分隔符)

我可以使用正則表達式拆分或匹配來實現嗎? 如果是這樣,正確的模式是什么? 對模式字符串的注釋將不勝感激。

此外,如果輸入的字符串無效,也可能引發異常或返回錯誤消息(請參見下面的注釋)。

謝謝。

您可以使用此模式...

string pattern = @"(\w+)\s*:\s*((?>[^\w\s\"'{[:]+|\w+\b(?!\s*:)|\s(?!\w+\s*:|$)|\[[^]]*]|{[^}]*}|\"(?>[^\"\\]|\\.)*\"|'(?>[^'\\]|\\.)*')+)\s*";

...有兩種方式:

  1. 使用Match方法,它將為您提供第1組中的鍵和第2組中的值的所需內容
  2. 使用Split方法,但必須刪除所有空結果。

如何構建模式的第二部分(在: )?

這個想法首先是要避免出現有問題的字符: [^\\w\\s\\"'{[:]+然后在特定情況下允許這些字符中的每一個:

  • \\w+\\b(?!\\s*:)不是關鍵的單詞
  • \\s(?!\\w+\\s*:|$)不在值末尾的空格(以修剪它們)
  • \\[[^]]*]內容用方括號括起來
  • {[^}]*}與大括號相同
  • 雙引號之間的"(?>[^"\\\\]|\\\\\\\\|\\\\.)*"內容(允許使用轉義的雙引號)
  • '(?>[^'\\\\]|\\\\\\\\|\\\\.)*'與單引號相同

請注意,可以避免在方括號或引號內出現冒號問題。

進入KeyC時,我不太確定要尋找什么。 您如何知道KeyB的字符串值何時結束而KeyC的字符串何時開始? “這是一個字符串”或換行符后是否有冒號? 這是一個示例,可以幫助您入門:

[TestMethod]
public void SplitString()
{
    string splitMe = "KeyA : SubComponent { SubKey : SubValue } KeyB:This's is a string";
    string pattern = "^(.*):(.*)({.*})(.*):(.*)";

    Match match = Regex.Match(splitMe, pattern);

    Assert.IsTrue(match.Success);
    Assert.AreEqual(6, match.Groups.Count); // 1st group is the entire match
    Assert.AreEqual("KeyA", match.Groups[1].Value.Trim());
    Assert.AreEqual("SubComponent", match.Groups[2].Value.Trim());
    Assert.AreEqual("{ SubKey : SubValue }", match.Groups[3].Value.Trim());
    Assert.AreEqual("KeyB", match.Groups[4].Value.Trim());
    Assert.AreEqual("This's is a string", match.Groups[5].Value.Trim());
}

這個正則表達式模式應該為您工作

\s*:\s*(?![^\[]*\])(?![^{]*})(?=(([^"]*"[^"]*){2})*$|[^"]+$)

當替換為

\n$0\n

演示

暫無
暫無

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

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