0

I want to know, with regex, if a list is well-written or not. A well-written list start with '[' and ends with ']' and can handle numbers or other lists or be empty.

Example of valid lists:

[1, 2, 3]
[1, [6, 9], 4]
[[1, 5], 2, [2, 7, [[]], 8, 9, [1]], []]

As you can see this is recursive. So, What regular expression should I use in this case?

  • I want to know if the entire list is valid or not. – André Kuljis Sep 18 '20 at 01:03
  • 3
    Duplicate of [Regular expression to match balanced parentheses](https://stackoverflow.com/questions/546433/regular-expression-to-match-balanced-parentheses), [Matching Nested Structures With Regular Expressions in Python](https://stackoverflow.com/q/1099178/8967612), and [Python: How to match nested parentheses with regex?](https://stackoverflow.com/q/5454322/8967612) – 41686d6564 Sep 18 '20 at 01:04
  • 1
    Python's regular expressions can't handle recursive brackets of arbitrary nesting level. You need a parser like e. g. Pyparsing or write a simple one. – Michael Butscher Sep 18 '20 at 01:05
  • 1
    If that is your syntax, Python's `ast` module can verify it, e.g. `ast.literal_eval('[1,[6,9],4]')`. It will raise an error if not balanced. You other literals, though, like `1.5` or `'a'` in the lists, so if you want strict checking use `pyparsing`. – Mark Tolonen Sep 18 '20 at 01:12
  • Assuming input is a string, you could do eval(input_str) and catch SyntaxError and report invalid if there is SyntaxError – ranjith Sep 18 '20 at 01:14
  • `eval` can be used to execute code. `ast.literal_eval` is safer. – Mark Tolonen Sep 18 '20 at 01:16

0 Answers0