7

I have the string CBG/FON/BCK-STO/A1/FDJ10 and I would like to extract the 2 last numbers (sometimes one, sometimes three).

I found some hint here: Splitting string (the last digits) in QGIS

but it doesn't work as expected.

The following formula:

regexp_substr("Field_Name", '(\\d+|\\d+.+)')

returns only 1 regardless of the number at the end.

Where can I find the principles for deduction the certain number of string or numbers from this string?

This thread Extracting only number from address in QGIS Attribute Table also doesn't work.

3 Answers 3

9

You can use the pattern (\\d+)$, which will look for 1 or more number followed by the end of the line.

If you omit the $, the first occurence of one or more number will be returned, i.e. the 1 of A1.

regexp_substr('CBG/FON/BCK-STO/A1/FDJ10','(\\d+)$')
-->10
2
  • Yes, but the pattern will change from i.e. FDJ10 to FDJ12, FDJ1, and so forth. How about this situation?
    – Geographos
    Feb 21, 2022 at 14:03
  • 1
    This pattern will always return the ending numbers (10,12,1 from your example).
    – JGH
    Feb 21, 2022 at 14:05
6

You can use:

regexp_substr( right("Field_Name", 3), '(\\d+)')

Examples:

regexp_substr( right( 'CBG/FON/BCK-STO/A1/FDJ1', 3), '(\\d+)') -- 1
regexp_substr( right( 'CBG/FON/BCK-STO/A1/FDJ12', 3), '(\\d+)') -- 12
regexp_substr( right( 'CBG/FON/BCK-STO/A1/FDJ123', 3), '(\\d+)') -- 123
5

Assuming the 2 to 3 digits are only located in the last part, you can try the following expression:

regexp_substr("Field_Name",'\\d{2,3}')

Here is the result:

enter image description here

Your Answer

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

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