Regex for MultiPolygon WKT

73 Views Asked by At

I am looking for a regex expression for validating a MultiPolygon in WKT format.

2

There are 2 best solutions below

0
On

This regular expression pattern matches MultiPolygon WKT format, which consists of one or more polygons, each of which consists of one or more rings (linear closed paths).

^MULTIPOLYGON\s*\(\s*\(\s*\(\s*(\(\s*-?\d+(?:\.\d+)?\s+-?\d+(?:\.\d+)?\s*\,?\s*)+\)\s*(,\s*\(\s*-?\d+(?:\.\d+)?\s+-?\d+(?:\.\d+)?\s*\,?\s*)*\)\s*\)\s*(,\s*\(\s*\(\s*(\(\s*-?\d+(?:\.\d+)?\s+-?\d+(?:\.\d+)?\s*\,?\s*)+\)\s*(,\s*\(\s*-?\d+(?:\.\d+)?\s+-?\d+(?:\.\d+)?\s*\,?\s*)*\)\s*\)\s*)*\)$

It assumes coordinates are in the order of longitude and latitude (i.e., "x y"). If the order is reversed, you can swap the order of the coordinate groups in the regular expression pattern

1
On

I came up with the following expression that matched with all my test values. Please let me know your inputs on how this can be improved or possible optimizations.

MULTIPOLYGON\s*\(\(\(\-?\d+(?:\.\d+)* \-?\d+(?:\.\d+)*(?:,\s*\s*\-?\d+(?:\.\d+)* \-?\d+(?:\.\d+)*)*\)(?:,\s*\(\-?\d+(?:\.\d+)* \-?\d+(?:\.\d+)*(?:,\s*\s*\-?\d+(?:\.\d+)* \-?\d+(?:\.\d+)*)*\))*\)(?:,\s*\(\(\-?\d+(?:\.\d+)* \-?\d+(?:\.\d+)*(?:,\s*\s*\-?\d+(?:\.\d+)* \-?\d+(?:\.\d+)*)*\)(?:,\s*\(\-?\d+(?:\.\d+)* \-?\d+(?:\.\d+)*(?:,\s*\s*\-?\d+(?:\.\d+)* \-?\d+(?:\.\d+)*)*\))*\))*\)

One limitation with this is that it cannot detect geometries with non-closed rings.