簡體   English   中英

正則表達式可以在“]”之后和“ [”之前找到任何內容

[英]Regex to find anything after ']' and before '['

我有一個正則表達式正在努力尋找文本文件中方括號之間的任何內容,這是這樣的:

Regex squareBrackets = new Regex(@"\[(.*?)\]");

我想創建一個正則表達式,基本上是在方括號之后選擇相反的正則表達式。 所以我想只是將它們交換一下?

Regex textAfterTitles = new Regex(@"\](.*?)\[");

但這是行不通的,正則表達式使我感到困惑-有人可以幫忙嗎? 干杯

您可以使用后

var textAfterTiles = new Regex(@"(?<=\[(.*?)\]).*");

如果您有多個這樣的方括號組,則可以將其與前瞻性結合使用,例如:

var textAfterTiles = "before [one] inside [two] after"

並且您想匹配" inside "" after" ,您可以這樣做:

new Regex(@"(?<=\[(.*?)\])[^\[]*");

相同的\\[(.*?)]正則表達式(我只需要在[ ]之前刪除多余的轉義反斜杠),甚至更好的regex是\\[([^]]*)] ,可用於拆分文本並獲取[...]以外的文本(如果與RegexOptions.ExplicitCapture修飾符一起使用):

var data = "A bracket is a tall punctuation mark[1] typically used in matched pairs within text,[2] to set apart or interject other text.";
Console.WriteLine(String.Join("\n", Regex.Split(data,@"\[([^]]*)]",RegexOptions.ExplicitCapture)));

C#演示的輸出:

A bracket is a tall punctuation mark
 typically used in matched pairs within text,
 to set apart or interject other text.

RegexOptions.ExplicitCapture標志使模式內的捕獲組不捕獲,因此,捕獲的文本不會輸出到結果拆分數組中。

如果您不必保留相同的正則表達式,只需刪除捕獲組,使用\\[[^]]*]進行拆分。

你可以試試這個

\]([^\]]*)\[

暫無
暫無

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

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