.net正则表达式捕获组加上其他一切

时间:2017-04-02 09:58:23

标签: c# .net regex

我正在尝试创建一个.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]

等等

2 个答案:

答案 0 :(得分:0)

    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

一个巨大的正则表达式很难理解,所以我只想在这上面使用更多的行。例如,这与所需文本匹配,然后将其从输入中删除。通过这种方式,您可以逐个捕获组,并且可以清楚地知道哪部分代码可以捕获哪些文本,以防将来需要修改正则表达式。

答案 1 :(得分:0)

正则表达式本身实际上非常简单:

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);
}

但问题是您通常无法捕获组的可变计数。 .NET虽然支持这一点,但你需要通过组和它们的捕获来实际获得所需的所有部分。完整代码如下所示:

ObjectMapper mapper   = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
ObjectWriter writer   = mapper.writer().withoutAttribute("property1").withoutAttribute("property2");
String       jsonText = writer.writeValueAsString(sourceObject);

这可以很容易地扩展到支持组名(虽然看起来不是很有价值)或其他标签。