3

I have a string field with housenumber which contains values like:

housenumber
5
12 a
15 b
18 c

What are the right expressions for the field calculator to write only the number in "field1" and only the string in "field2":

field1 field2
5 NULL
12 a
15 b
18 c

I guess regular expressions. But how to implement it?

enter image description here

1
  • 1
    I wouldn't use regex for this, but it's certainly possible. What have you tried?
    – Vince
    Jul 28 at 10:50
7

Extract information with a regular expression is always a bit tricky without having all the data, and can lead to unexpected results. For example what should happen if the field has data like 'a 22 a'.

Taken that into account and with the sample data that you provide you can try with these two regular expressions.

# For field1
regexp_substr("hausnummer", '[0-9]*')

# For field2
regexp_substr("hausnummer", '[[:alpha:]]+')

enter image description here

BTW there is a wonderful online tool that you can use to test regular expressions for different engines/languages

5
  • Find all consecutive numbers (first occurrences):
    regexp_substr( "hausnummer", '(\\d+)' )
    
  • Find all consecutive characters (first occurrences, in range a - z & A - Z):
    regexp_substr( "hausnummer", '([a-zA-Z]+)' )
    
2
  • 1
    Thanks! The first expressions leads to a field with no values at all. But the second expressions works fine! Jul 28 at 11:02
  • 1
    @EnzoBaldini ah, sorry, you need to escape with (double) \\. Corrected.
    – geozelot
    Jul 28 at 11:15
1

I would use

f1 = left("hausnummer",strpos("hausnummer",' ')-1)

f2 = right("hausnummer",length("hausnummer")-strpos("hausnummer",' '))

2
  • Thanks! The first expressions works fine! But the second expression for f2 leads to the same result as the first... Jul 28 at 11:00
  • A good try, but what to do if the house number is 22a and not 22 a?
    – Taras
    Jul 28 at 11:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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