11223342124 11223342124 - 1 month ago 20
Javascript Question

Matrix validation format

I am making page for matrix multiplication and I need to validate those matrices. Currently I have regex that accepts this format:

[[1,2,3],[4,5,6],[7,8,9]]
but it should accept this as well:
[[1,2,3]]
.

^\[(\[[\d+,\s*]+\],)+\[[\d+,]+]]$


What should I do? How it can match single array and group of them too?

Answer

I assume you want something like this:

^\[?(?:(?:\[(?:(?:[0-9]{1,}\,?){1,})\])\,?){1,}\]?$

To match all these:

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

Regex 101 here: https://regex101.com/r/tsS0G3/3

Comments