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)'.

Taras
  • 32,823
  • 4
  • 66
  • 137
GrahamD
  • 241
  • 1
  • 2
  • 3

5 Answers5

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.

Cyrille
  • 300
  • 2
  • 10
underdark
  • 84,148
  • 21
  • 231
  • 413
12

The proper syntax is:

replace([field_name], '(B)', 'Country')
Taras
  • 32,823
  • 4
  • 66
  • 137
eseglem
  • 800
  • 1
  • 5
  • 18
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

Taras
  • 32,823
  • 4
  • 66
  • 137
maliheh
  • 51
  • 1
  • 1
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

Taras
  • 32,823
  • 4
  • 66
  • 137
Dan R
  • 143
  • 1
  • 11
1

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

Field find/replace

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