14 Search and replace
To specifically replace data in an attribute field, you can use the regexp_replace()
function in the QGIS field calculator. This function allows you to search for text patterns within a field and replace them with new text. Both simple terms and regular expressions can be used to perform complex replacements.
Syntax:
regexp_replace(""Field name", 'Search pattern', 'Replacement text')
"Field name"
: The attribute field in which the replacement is to be carried out.'Search pattern'
: The term or text pattern that you want to replace. This can be a simple text or a regular expression.'Replacement text'
: The text that is to replace the term or pattern found.
Example:
If you want to replace the term Term1
with Term2
in an attribute field called “Field name”, the expression is as follows:
regexp_replace("Field name", 'term1', 'term2')
In this example, the function searches for occurrences of term1
in each data record of the “Field name” field and replaces them with term2
.
Application example:
Suppose the attribute field “Field name” contains a list of tree species and you want to replace all occurrences of the term “oak” with “beech”. The expression in the field calculator would then look like this:
regexp_replace("Field name", 'oak', 'beech')
After execution, all entries containing the term “oak” are automatically replaced by “beech”.
Advantages of regexp_replace()
:
- Flexibility: In addition to simple terms, complex text patterns can also be defined using regular expressions to capture specific or recurring patterns.
- Precision: By using regular expressions, you can ensure that only the desired occurrences are replaced.
- Automation: The function can be used for all data records in an attribute field at the same time, making manual adjustments unnecessary.
Note:
If you only want to replace simple terms without using regular expressions, you can also use the replace()
function, which is more straightforward for such cases. The expression would then look like this:
replace("Field name", 'term1', 'term2')
However, the regexp_replace()
function offers more possibilities, as it recognizes and changes patterns and complex text structures.