5

On the QGIS Field calculator, I am trying to remove from a string the text that is inside parentheses using regexp_replace.

While it is not a problem to remove the text from a string that contains only one parentheses group (using

regexp_replace('Steep (61° to 84°)','[(](.*)?[)]','')

it gives "Steep" as a result.

I am having some issues with extracting the text from a string where are present multiple parentheses, e.g.,

'Steep (61° to 84°), Vertical / Near Vertical (85° to 90°)'

From the above string, I would like to obtain

'Steep, Vertical / Near Vertical'

but if I try to use the same regex I obtain again only "steep", because for the system the closing parenthesis is the one at the end of the string.

3
  • What happens when you run your regexp_replace() on the whole string?
    – Erik
    Oct 12, 2022 at 11:06
  • Hi, the result is the same as the previous: steep , because for the expression the last ) is at the end of the string.
    – Val P
    Oct 12, 2022 at 11:17
  • Have you tried running the regexp_replace() on substrings, which you define by whether they are before or after the comma?
    – Erik
    Oct 12, 2022 at 11:20

2 Answers 2

8

You can expand your group to include the [(] and [)] by moving the inner parentheses outwards, like so:

'([(].*?[)])'

The expression becomes:

regexp_replace('Steep (61° to 84°), Vertical / Near Vertical (85° to 90°)','([(].*?[)])','')

enter image description here

5
  • Thanks a lot for your answer. It solves my issue.
    – Val P
    Oct 12, 2022 at 11:24
  • Glad to help. There is a trailing space after Steep but it should be fairly simple to remove if you need to.
    – Matt
    Oct 12, 2022 at 11:26
  • Prefixing the pattern with a space seems to do the trick: ' ([(].*?[)])'
    – Matt
    Oct 12, 2022 at 11:29
  • I was using a simple replace(xxx, ' ,',',') but this is definitely a better solution. Thanks again.
    – Val P
    Oct 12, 2022 at 11:38
  • As long as the data is formatted consistently for every row, with both sets of parentheses having a space before them. Otherwise, your method might be safer :)
    – Matt
    Oct 12, 2022 at 11:45
6

With this expression also take into account the space after Steep:

regexp_replace(
  'Steep (61° to 84°), Vertical / Near Vertical (85° to 90°)',
  ' \\(\\d+° to \\d+°\\)','')

enter image description here

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.