[GIS] Replace non-ASCII characters in QGIS Field Calculator

field-calculatorpythonqgisregular expression

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?

Best Answer

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.