Regular expression to determine the value between brackets "()"?

I wrote regex very poorly.

I am trying to get the value between the brackets "()". Something like below ...

$a = "POLYGON((1 1,2 2,3 3,1 1))"; preg_match_all("/\((.*)\)/U", $a, $pat_array); print_r($pat_array); 

But it will give me elements like ...

 Array ( [0] => Array ( [0] => ((1 1,2 2,3 3,1 1) ) [1] => Array ( [0] => (1 1,2 2,3 3,1 1 ) ) 

But I want to get "1 1.2 2.3 3.1 1" as an output.

I know that we can trim the brackets after receiving this output. But it will be great if it is done using regex.

Thanks in advance.


Solution: according to @anubhava answer:

Using the regular expression @anubhava .

Example:

 $a = "POLYGON((1 1,2 2,3 3,1 1),(1 1,2 2,3 3,1 1),(1 1,2 2,3 3,1 1))"; 

And if the print result of this regular expression is the same ...

 Array ( [0] => Array ( [0] => ((1 1,2 2,3 3,1 1) [1] => (1 1,2 2,3 3,1 1) [2] => (1 1,2 2,3 3,1 1)) ) [1] => Array ( [0] => 1 1,2 2,3 3,1 1 [1] => 1 1,2 2,3 3,1 1 [2] => 1 1,2 2,3 3,1 1 ) ) 

Look at the second element of the array, it is exactly the way we want.

FYI: I used it to extract GEOMETRY data from POLYGON from a MySQL database, and then processed it with an array to get all the latitude and longitude of all nodes of the polygon.

+5
source share
2 answers

Use the negation-based regex template and get the result from captured group # 1:

 preg_match_all('/\(+([^()]*)\)+/', $a, $pat_array); print_r($pat_array[1]); 

[^()]* will match any char that is not ( or ) .

Output:

 Array ( [0] => 1 1,2 2,3 3,1 1 ) 
+3
source

Use lookarounds

 preg_match_all("/(?<=\()[^()]*(?=\))/U", $a, $pat_array); 

See the demo.

https://regex101.com/r/vV1wW6/42

+1
source

Source: https://habr.com/ru/post/1232610/


All Articles