3

To get a list of coordinates from a polygon and remove unwanted parts from the resulting string, the following expression works fine to remove the string elements 'Polygon', spaces and opening brackets (:

regexp_replace(
    geom_to_wkt($geometry), 
    '(Polygon)( )(\\(*)',
    ''
)

However, I struggle to find a way to similarily remove closing brackets ). To remove only these brackets, this regex works fine: '(\\))'. But when I add this as another capturing group in line 3 of the expression like '(Polygon)( )(\\(*)(\\))', nothing is replaced at all.

How can I remove all unnecessary characters, including closing brackets? For context, see here.

2
  • 1
    So, if I suggest you this array_foreach(string_to_array(replace(replace(geom_to_wkt($geometry), 'Polygon ((', ''), ')', ''), ', '), string_to_array(@element, ' ')) it probably won't help you much ?
    – Taras
    Mar 23, 2022 at 9:11
  • Indeed, this is not what I was looking for. Like this, I could have used a simple replace function: replace (regexp_replace( geom_to_wkt($geometry), '(Polygon)( )(\\(*)', '' ),')','')
    – Babel
    Mar 23, 2022 at 12:44

2 Answers 2

4

Other solution:

regexp_replace(
     geom_to_wkt($geometry),
    '(Polygon \\(\\()(.+)(\\)\\))',
    '\\2')

enter image description here

3

This will remove all alphabetic characters and (round) parentheses:

regexp_replace(
    geom_to_wkt($geometry), 
    '[A-Za-z()]',
    ''
)

As pointed out by @pigreco, the leading space can be removed by wrapping regexp_replace in the trim function.

trim(
    regexp_replace(
        geom_to_wkt($geometry), 
        '[A-Za-z()]',
        ''
    )
)
5
  • 3
    a space is required, otherwise the output string would contain a leading space
    – pigreco
    Mar 23, 2022 at 10:19
  • I saw that you added the space in [ A-Za-z()], but this removes the space between the coordinates too !!!
    – pigreco
    Mar 23, 2022 at 10:36
  • 1
    I suggest to use the trim function like this, so you remove the white space at the beginning trim(regexp_replace(geom_to_wkt($geometry),[A-Za-z()]',''))
    – pigreco
    Mar 23, 2022 at 11:28
  • 1
    Apologies, I was away from the computer and quickly made the edit on my phone. Lesson learned and thanks for correction.
    – Matt
    Mar 23, 2022 at 11:39
  • 2
    Changed accepted answer to @pigreco's one for his efforts both in his answer as well as here, even though both answers would have deserved it. Matt's solution together with the trim function is probably what I would use.
    – Babel
    Mar 23, 2022 at 12:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.