Search code examples
regexbracketsalteryx

Regex to match everything between multiple set of brackets


I am trying to match everything between multiple set of brackets

Example of data

[[42.30722,-83.181125],[42.30722,-83.18112667],[42.30722167,-83.18112667,[42.30721667,-83.181125],[+42.30721667,-83.181125]]

I need to match everything within the inner brackets as below

42.30722,-83.181125,
42.30722,-83.18112667,
42.30722167,-83.18112667,
42.30721667,-83.181125,
+42.30721667,-83.181125

How do I do that. I tried \[([^\[\]]|)*\] but it gives me values with brackets. Can anybody please help me with this. Thanks in advance


Solution

  • Seems like one of them is missing a bracket maybe, or if not, maybe some expression similar to:

    \[([+-]?\d+\.\d+)\s*,\s*([+-]?\d+\.\d+)\s*\]?
    

    might be OK to start with.

    Test

    import re
    
    expression = r"\[([+-]?\d+\.\d+)\s*,\s*([+-]?\d+\.\d+)\s*\]?"
    string = """
    [[42.30722,-83.181125],[42.30722,-83.18112667],[42.30722167,-83.18112667,[42.30721667,-83.181125],[+42.30721667,-83.181125]]
    """
    
    print([list(i) for i in re.findall(expression, string)])
    print(re.findall(expression, string))
    

    Output

    [['42.30722', '-83.181125'], ['42.30722', '-83.18112667'], ['42.30722167', '-83.18112667'], ['42.30721667', '-83.181125'], ['+42.30721667', '-83.181125']]
    [('42.30722', '-83.181125'), ('42.30722', '-83.18112667'), ('42.30722167', '-83.18112667'), ('42.30721667', '-83.181125'), ('+42.30721667', '-83.181125')]
    

    If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.