3

I have some data which is built like this:

a,bbb,ccc

where bbb and ccc vary in length.

I want to extract the last segment of the string, after the second ",". Using the Function Editor:

from qgis.core import *
from qgis.gui import *

@qgsfunction(args='auto', group='Custom')
def sp_split(value1):
    return value1.split(",")[2]

I save it as a function called sp_split, but when I call it in the expression with a field for a value, it doesn't recognize it. enter image description here

Pressing More Info gives me this explanation:

Eval Error:
sp_split() takes exactly 1 argument (3 given)

What might be the reason for that? I'm at a loss here. I'm using the function because of the split, if there is another way of using the built-in expression to retain the "ccc" part, I'll gladly use it.

9
  • I don't have access to QGIS now, but check for the regular expressions functions. You need to match something like: .*,.*,(.*) Jul 19, 2016 at 22:37
  • Click on (more info) it will tell you what is wrong.
    – Nathan W
    Jul 20, 2016 at 2:30
  • @NathanW Updated the question, Eval Error: sp_split() takes exactly 1 argument (3 given)
    – HDunn
    Jul 20, 2016 at 3:26
  • Make it this sp_split(value1, feature, parent)
    – Nathan W
    Jul 20, 2016 at 3:32
  • @NathanW Looks like I'm back to square one, now error reads 'QgsExpressionFunction' object has no attribute 'split'. Which is weird, as typing the function does give me "split" in the autocomplete suggestion
    – HDunn
    Jul 20, 2016 at 3:39

1 Answer 1

3

I think you need to add from qgis.utils import qgsfunction into your code. You can also remove the other imports as they're not necessary. So something like this should work:

from qgis.utils import qgsfunction

@qgsfunction(args="auto", group='Custom')
def sp_split(value1, feature, parent):
    return value1.split(",")[2]
3
  • 1
    Yes, that's it.
    – HDunn
    Jul 26, 2016 at 12:59
  • @HDunn - Awesome, glad it worked =)
    – Joseph
    Jul 26, 2016 at 12:59
  • 1
    Also, caiohamamura method worked as well, except that some of the text values concatenations had only one "," in between the parts. So I was planning on just calling it up using [-1].
    – HDunn
    Jul 26, 2016 at 13:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.