How to split text attribute by characters in QGIS?
Yes you can.
Use the Field calculator with the following expression:
left( "Name", strpos( "Name" ,'-'))
The strpos() function will return the index position of the first '-' character and the left() function "trims" the string before that position.
You can use the Field calculator with the following expression:
string_to_array("Nombre", ' ')
The string_to_array() function splits string into an array using supplied delimiter.
If you want a some position of the array, you can add the position and it will return the value. like this:
string_to_array("Nombre", ' ')[2]
Possible solution by means of PyQGIS.
Let's assume there is a point layer called "some_points"
with it's attribute table, see image below.
Proceed with Plugins > Python Console > Show Editor
and paste the script below
from PyQt5.QtCore import QVariant
layer = iface.activeLayer()
if not layer.isValid():
print("Layer failed to load!")
layer_provider = layer.dataProvider()
layer_provider.addAttributes([QgsField("Test", QVariant.String)])
layer.updateFields()
features=layer.getFeatures()
layer.startEditing()
for f in features:
attrs = {2: f['info'].split('-')[0]}
layer_provider.changeAttributeValues({f.id(): attrs})
layer.commitChanges()
The output will be looking
References:
- QGIS Python Tutorial: How to Add/Delete Field and Updating Attribute Value
- PyQGIS developer cookbook