24

Within an attribute table, I'm trying to replace one string with another using the replace function. As an example, there are a number of features whose field "NAME" contains the string '(B)' and I'm wanting to replace this with the word 'County'. I'm selecting the 'update existing field' checkbox and using the following expression

 replace('(B)', '(B)', 'County')

The end result is that the field "NAME" for every feature is replaced by 'County' irrespective of whether or not the field "NAME" originally contained the string '(B)'.

1

5 Answers 5

37
replace( '(B)','(B)','County')

tells QGIS to replace the '(B)' in '(B)' with 'Country'.

You want

replace("Name",'(B)','Country')

= replace the '(B)' in "Name" with 'Country'.

Note that the double quotes indicate a field name while the single quotes refer to a static string. These are not interchangeable.

1
  • 1
    @GrahamD please accept the answer if it solved your problem
    – underdark
    Commented Jan 9, 2017 at 20:53
12

The proper syntax is:

replace([field_name], '(B)', 'Country')
5

Firstly, open the Field Calculator and select the replace function from the string option like the following picture:

enter image description here

Secondly, tells QGIS to replace the replace ("Field Name", '(B)', 'Country'). For example in this case

replace("MES_TIP", 'T', 'Rock')

Thirdly, please choose the output field type: text(string), and then determine the field name

enter image description here

1

There is also a small plugin available now, which wraps regex_replace in a small GUI:

Field find/replace

1
  • It's painfully slow... not usable with larger datasets, and does not have a cancel button to stop action. Quite bad "plugin"
    – sys49152
    Commented Apr 19, 2023 at 8:04
1

The interface looks a little different now and you have to select the column from the menu in the drop-down on the left-abc name

I also noted that words in the single quotations have to be exact including no extra spaces. (which stumped me briefly)

I was replacing the word Road with Rd. in this example.

replace("name", 'Road', 'Rd.') 

Press Update Filtered to make the change. It can take a while...as this OSM file did.

Filtering out a huge table would help speed up the replacement process.

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.