Regex for matching a character, but not when it's enclosed in square bracket

前端 未结 2 1509
别那么骄傲
别那么骄傲 2020-11-29 11:37

Input string:

[Wsg-Fs]-A-A-A-Cgbs-Sg7-[Wwg+s-Fs]-A-A-Afk-Cgbs-Sg7

Desired output is a string array:

[Wsg-Fs] A A A Cgbs Sg7         


        
相关标签:
2条回答
  • 2020-11-29 12:15

    Assuming there are no nested square brackets, you can use the following to only match - characters that are outside of square brackets:

    -(?![^\[]*\])
    

    Example: http://regex101.com/r/sX5hZ2

    This uses a negative lookahead, with the logic that if there is a closing square bracket before any opening square brackets, then the - that we tried to match is inside of brackets.

    0 讨论(0)
  • 2020-11-29 12:34

    Resurrecting this ancient question to offer another solution, since the current one only checks that a splitting - is not followed by a ], which does not guarantee that it is enclosed in brackets.

    \[[^\]]*\]|(-)
    

    Then splitting on Group 1 (see the Group 1 captures in the bottom right panel of the demo)

    To split on Group 1, we first replace Group 1 with something distinctive, such as SPLIT_HERE, then we split on SPLIT_HERE

    using System;
    using System.Text.RegularExpressions;
    using System.Collections.Specialized;
    class Program
    {
    static void Main() {
    string s1 = @"[Wsg-Fs]-A-A-A-Cgbs-Sg7-[Wwg+s-Fs]-A-A-Afk-Cgbs-Sg7";
    var myRegex = new Regex(@"\[[^\]]*\]|(-)");
    var group1Caps = new StringCollection();
    
    string replaced = myRegex.Replace(s1, delegate(Match m) {
    if (m.Groups[1].Value == "") return m.Groups[0].Value;
    else return "SPLIT_HERE";
    });
    
    string[] splits = Regex.Split(replaced,"SPLIT_HERE");
    foreach (string split in splits) Console.WriteLine(split);
    
    Console.WriteLine("\nPress Any Key to Exit.");
    Console.ReadKey();
    
    } // END Main
    } // END Program
    

    Here's a full working online demo

    Reference

    How to match pattern except in situations s1, s2, s3

    How to match a pattern unless...

    0 讨论(0)
提交回复
热议问题