[英].net Regex to capture groups plus everything else
我正在嘗試創建一個.net正則表達式,它將整個字符串捕獲到不同的組中。 捕獲組很容易,但是捕獲其余的部分超出了我的范圍。
[BBCode]標記可能出現在字符串中的任何地方,或者是唯一的,或者根本不存在。 字符串中也可能有[方括號]。
具有組名將是一個獎勵。
class Program
{
static void Main(string[] args)
{
string input = "thinking [ of using ] BBCode format [A=16] and [E=2] here [V=8] and so on";
string regexString = @"((\[A=[0-9]+\])|(\[E=[0-9]+\])|(\[V=[0-9]+\]))";
MatchCollection matches = Regex.Matches(input, regexString);
foreach (Match match in matches)
{
Console.WriteLine(match.Value);
}
}
}
我得到的結果是(每行一組)
想[使用] BBCode格式
[A = 16]
和
[E = 2]
這里
[V = 8]
等等
string input = "thinking of[ using BBCode format [A=16] here [E=2] and [V=8] and so on";
var firstText= Regex.Match(input, @".+?(?=\[A)"); //Match until [A
Console.WriteLine(firstText); //thinking of[ using BBCode format
input = Regex.Replace(input, @".+?(?=\[A)", "");
var AValue = Regex.Match(input, @"\[A=[0-9]+\]"); //Match the value of A
input = Regex.Replace(input, @"\[A=[0-9]+\] ", "");
Console.WriteLine(AValue); //[A=16]
var AText = Regex.Match(input, @".+?(?=\[)"); //Match the text after A
Console.WriteLine(AText); // here
一個巨大的正則表達式很難理解,因此我將在此使用更多行。 例如,這與所需文本匹配,然后將其從輸入中刪除。 這樣,您就可以一個一個地捕獲組,並且很清楚,代碼的哪一部分可以捕獲哪個文本,以防將來需要修改正則表達式。
正則表達式本身實際上非常簡單:
var input = "thinking [ of using ] BBCode format [A=16] and [E=2] here [V=8] and so on";
var pattern = @"^(?:(.*?)(\[[AEV]=\d+\]))*(.*?)$";
var match = Regex.Match(input, pattern);
但是,問題在於您通常無法捕獲可變數量的組。 雖然.NET支持此功能,但是您需要遍歷各個組及其捕獲,才能真正獲得所需的所有部分。 完整的代碼如下所示:
var input = "thinking [ of using ] BBCode format [A=16] and [E=2] here [V=8] and so on";
var pattern = @"^(?:(.*?)(\[[AEV]=\d+\]))*(.*?)$";
var match = Regex.Match(input, pattern);
var captures =
match
.Groups
.OfType<Group>()
.Skip(1) // first Group is the whole Match itself
.SelectMany(g => g.Captures.OfType<Capture>())
.OrderBy(c => c.Index); // order the captures by index to get them in appearance order, not in group order
foreach (var capture in captures)
{
System.Console.WriteLine(capture.Value);
}
可以輕松地擴展它以支持組名(雖然看起來不太有價值)或其他標簽。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.