5

I want to replace all non-standard characters from fields in a dbf table in QGIS.

From https://stackoverflow.com/questions/20078816/replace-non-ascii-characters-with-a-single-space

I see we can use something like

re.sub(r'[^\x00-\x7F]+','_',  "New_Name" )

But I am not sure how to use this in the the Expression or Function Editor module.

So I have a column called "New_Name" which I want the !@#$%^&*()~`+ etc signs removed and replaced with _

Can RE be used or do we need to specify each value to replace using CASE WHEN or Replace -the solution in RE is better if it can be done in QGIS Field Calculator using the regexp_replace expression?

5
  • 3
    have you tried using regexp_replace("field",'\W','_'), might be simpler? (not tried it but worth a go)
    – Steven Kay
    May 24, 2016 at 6:30
  • Didn't know you could - I get "An error occurred while evaluating the calculation string: Invalid regular expression '?': bad repetition syntax" this is using [regexp_replace( "New_Name" ,'\W','_')] @StevenKay
    – GeorgeC
    May 24, 2016 at 6:36
  • 2
    It looks as if \W might not be supported in regexp_replace(), but it should work in Python's re.sub() ( And I should have used \W+ )
    – Steven Kay
    May 24, 2016 at 6:41
  • 3
    @StevenKay - You're close! You just need a double backslash for \\W so the expression should read regexp_replace( "field", '\\W+', '_' ). Consider posting it as an answer :)
    – Joseph
    May 24, 2016 at 9:28
  • 3
    @Joseph thanks. That worked perfectly. Steven why don't you add it in as an answer as mentioned by Joseph :-)
    – GeorgeC
    May 24, 2016 at 10:38

1 Answer 1

6

You can use the \W (upper case W) to match any non-alphanumeric characters.

If using regexp_replace() it seems you need to escape the backslash, so it becomes \\W (thanks, Joseph!)

For example

regexp_replace( '=+&hello%%£world','\\W+','_')

returns

_hello_world

If using the python equivalent function re.sub(), you probably won't need to escape the backslash.

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.